repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
spiral/orm
source/Spiral/ORM/Entities/Nodes/AbstractNode.php
AbstractNode.ensurePlaceholders
private function ensurePlaceholders(array &$data) { //Let's force placeholders for every sub loaded foreach ($this->nodes as $name => $node) { $data[$name] = $node instanceof ArrayInterface ? [] : null; } }
php
private function ensurePlaceholders(array &$data) { //Let's force placeholders for every sub loaded foreach ($this->nodes as $name => $node) { $data[$name] = $node instanceof ArrayInterface ? [] : null; } }
[ "private", "function", "ensurePlaceholders", "(", "array", "&", "$", "data", ")", "{", "//Let's force placeholders for every sub loaded", "foreach", "(", "$", "this", "->", "nodes", "as", "$", "name", "=>", "$", "node", ")", "{", "$", "data", "[", "$", "name...
Create placeholders for each of sub nodes. @param array $data
[ "Create", "placeholders", "for", "each", "of", "sub", "nodes", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Nodes/AbstractNode.php#L398-L404
train
spiral/orm
source/Spiral/ORM/Entities/Nodes/AbstractNode.php
AbstractNode.trackReference
private function trackReference(string $key) { if (!in_array($key, $this->columns)) { throw new NodeException("Unable to create reference, key {$key} does not exist"); } if (!in_array($key, $this->trackReferences)) { //We are only tracking unique references $this->trackReferences[] = $key; } }
php
private function trackReference(string $key) { if (!in_array($key, $this->columns)) { throw new NodeException("Unable to create reference, key {$key} does not exist"); } if (!in_array($key, $this->trackReferences)) { //We are only tracking unique references $this->trackReferences[] = $key; } }
[ "private", "function", "trackReference", "(", "string", "$", "key", ")", "{", "if", "(", "!", "in_array", "(", "$", "key", ",", "$", "this", "->", "columns", ")", ")", "{", "throw", "new", "NodeException", "(", "\"Unable to create reference, key {$key} does no...
Add key to be tracked @param string $key @throws NodeException
[ "Add", "key", "to", "be", "tracked" ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Nodes/AbstractNode.php#L413-L423
train
spiral/orm
source/Spiral/ORM/Entities/Loaders/RootLoader.php
RootLoader.withColumns
public function withColumns(array $columns): self { $loader = clone $this; $loader->columns = array_merge( [$loader->schema[Record::SH_PRIMARY_KEY]], $columns ); return $loader; }
php
public function withColumns(array $columns): self { $loader = clone $this; $loader->columns = array_merge( [$loader->schema[Record::SH_PRIMARY_KEY]], $columns ); return $loader; }
[ "public", "function", "withColumns", "(", "array", "$", "columns", ")", ":", "self", "{", "$", "loader", "=", "clone", "$", "this", ";", "$", "loader", "->", "columns", "=", "array_merge", "(", "[", "$", "loader", "->", "schema", "[", "Record", "::", ...
Columns to be selected, please note, primary will always be included, DO not include column aliases in here, aliases will be added automatically. Creates new loader tree copy. @param array $columns @return RootLoader
[ "Columns", "to", "be", "selected", "please", "note", "primary", "will", "always", "be", "included", "DO", "not", "include", "column", "aliases", "in", "here", "aliases", "will", "be", "added", "automatically", ".", "Creates", "new", "loader", "tree", "copy", ...
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Loaders/RootLoader.php#L70-L79
train
spiral/orm
source/Spiral/ORM/Entities/Relations/MultipleRelation.php
MultipleRelation.matchOne
public function matchOne($query) { foreach ($this->loadData(true)->instances as $instance) { if ($this->match($instance, $query)) { return $instance; } } return null; }
php
public function matchOne($query) { foreach ($this->loadData(true)->instances as $instance) { if ($this->match($instance, $query)) { return $instance; } } return null; }
[ "public", "function", "matchOne", "(", "$", "query", ")", "{", "foreach", "(", "$", "this", "->", "loadData", "(", "true", ")", "->", "instances", "as", "$", "instance", ")", "{", "if", "(", "$", "this", "->", "match", "(", "$", "instance", ",", "$...
Fine one entity for a given query or return null. Method will autoload data. Example: ->matchOne(['value' => 'something', ...]); @param array|RecordInterface|mixed $query Fields, entity or PK. @return RecordInterface|null
[ "Fine", "one", "entity", "for", "a", "given", "query", "or", "return", "null", ".", "Method", "will", "autoload", "data", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/MultipleRelation.php#L108-L117
train
spiral/orm
source/Spiral/ORM/Entities/Relations/MultipleRelation.php
MultipleRelation.matchMultiple
public function matchMultiple($query) { $result = []; foreach ($this->loadData(true)->instances as $instance) { if ($this->match($instance, $query)) { $result[] = $instance; } } return new \ArrayIterator($result); }
php
public function matchMultiple($query) { $result = []; foreach ($this->loadData(true)->instances as $instance) { if ($this->match($instance, $query)) { $result[] = $instance; } } return new \ArrayIterator($result); }
[ "public", "function", "matchMultiple", "(", "$", "query", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "loadData", "(", "true", ")", "->", "instances", "as", "$", "instance", ")", "{", "if", "(", "$", "this", "->"...
Return only instances matched given query, performed in memory! Only simple conditions are allowed. Not "find" due trademark violation. Method will autoload data. Example: ->matchMultiple(['value' => 'something', ...]); @param array|RecordInterface|mixed $query Fields, entity or PK. @return \ArrayIterator
[ "Return", "only", "instances", "matched", "given", "query", "performed", "in", "memory!", "Only", "simple", "conditions", "are", "allowed", ".", "Not", "find", "due", "trademark", "violation", ".", "Method", "will", "autoload", "data", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/MultipleRelation.php#L129-L139
train
spiral/orm
source/Spiral/ORM/Entities/Relations/MultipleRelation.php
MultipleRelation.initInstances
protected function initInstances(): self { if (is_array($this->data) && !empty($this->data)) { //Iterates and instantiate records $iterator = new RecordIterator($this->data, $this->class, $this->orm); foreach ($iterator as $item) { if (in_array($item, $this->instances, true)) { //Skip duplicates continue; } $this->instances[] = $item; } } //Memory free $this->data = null; return $this; }
php
protected function initInstances(): self { if (is_array($this->data) && !empty($this->data)) { //Iterates and instantiate records $iterator = new RecordIterator($this->data, $this->class, $this->orm); foreach ($iterator as $item) { if (in_array($item, $this->instances, true)) { //Skip duplicates continue; } $this->instances[] = $item; } } //Memory free $this->data = null; return $this; }
[ "protected", "function", "initInstances", "(", ")", ":", "self", "{", "if", "(", "is_array", "(", "$", "this", "->", "data", ")", "&&", "!", "empty", "(", "$", "this", "->", "data", ")", ")", "{", "//Iterates and instantiate records", "$", "iterator", "=...
Init pre-loaded data. @return HasManyRelation|self
[ "Init", "pre", "-", "loaded", "data", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/MultipleRelation.php#L174-L194
train
spiral/orm
source/Spiral/ORM/Entities/Relations/Traits/MatchTrait.php
MatchTrait.match
protected function match(RecordInterface $record, $query): bool { if ($record === $query) { //Strict search return true; } //Primary key comparision if (is_scalar($query) && $record->primaryKey() == $query) { return true; } //Record based comparision if ($query instanceof RecordInterface) { //Matched by PK (assuming both same class) if (!empty($query->primaryKey()) && $query->primaryKey() == $record->primaryKey()) { return true; } //Matched by content (this is a bit tricky!) if ($record->packValue() == $query->packValue()) { return true; } return false; } //Field intersection if (is_array($query) && array_intersect_assoc($record->packValue(), $query) == $query) { return true; } return false; }
php
protected function match(RecordInterface $record, $query): bool { if ($record === $query) { //Strict search return true; } //Primary key comparision if (is_scalar($query) && $record->primaryKey() == $query) { return true; } //Record based comparision if ($query instanceof RecordInterface) { //Matched by PK (assuming both same class) if (!empty($query->primaryKey()) && $query->primaryKey() == $record->primaryKey()) { return true; } //Matched by content (this is a bit tricky!) if ($record->packValue() == $query->packValue()) { return true; } return false; } //Field intersection if (is_array($query) && array_intersect_assoc($record->packValue(), $query) == $query) { return true; } return false; }
[ "protected", "function", "match", "(", "RecordInterface", "$", "record", ",", "$", "query", ")", ":", "bool", "{", "if", "(", "$", "record", "===", "$", "query", ")", "{", "//Strict search", "return", "true", ";", "}", "//Primary key comparision", "if", "(...
Match entity by field intersection, instance values or primary key. @param RecordInterface $record @param RecordInterface|array|mixed $query @return bool
[ "Match", "entity", "by", "field", "intersection", "instance", "values", "or", "primary", "key", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/Traits/MatchTrait.php#L25-L58
train
spiral/orm
source/Spiral/ORM/ORM.php
ORM.schemaBuilder
public function schemaBuilder(bool $locate = true): SchemaBuilder { /** * @var SchemaBuilder $builder */ $builder = $this->getFactory()->make(SchemaBuilder::class, ['manager' => $this->manager]); if ($locate) { foreach ($this->locator->locateSchemas() as $schema) { $builder->addSchema($schema); } foreach ($this->locator->locateSources() as $class => $source) { $builder->addSource($class, $source); } } return $builder; }
php
public function schemaBuilder(bool $locate = true): SchemaBuilder { /** * @var SchemaBuilder $builder */ $builder = $this->getFactory()->make(SchemaBuilder::class, ['manager' => $this->manager]); if ($locate) { foreach ($this->locator->locateSchemas() as $schema) { $builder->addSchema($schema); } foreach ($this->locator->locateSources() as $class => $source) { $builder->addSource($class, $source); } } return $builder; }
[ "public", "function", "schemaBuilder", "(", "bool", "$", "locate", "=", "true", ")", ":", "SchemaBuilder", "{", "/**\n * @var SchemaBuilder $builder\n */", "$", "builder", "=", "$", "this", "->", "getFactory", "(", ")", "->", "make", "(", "SchemaBu...
Create instance of ORM SchemaBuilder. @param bool $locate Set to true to automatically locate available records and record sources sources in a project files (based on tokenizer scope). @return SchemaBuilder @throws SchemaException
[ "Create", "instance", "of", "ORM", "SchemaBuilder", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/ORM.php#L158-L176
train
spiral/orm
source/Spiral/ORM/ORM.php
ORM.getFactory
protected function getFactory(): FactoryInterface { if ($this->container instanceof FactoryInterface) { return $this->container; } return $this->container->get(FactoryInterface::class); }
php
protected function getFactory(): FactoryInterface { if ($this->container instanceof FactoryInterface) { return $this->container; } return $this->container->get(FactoryInterface::class); }
[ "protected", "function", "getFactory", "(", ")", ":", "FactoryInterface", "{", "if", "(", "$", "this", "->", "container", "instanceof", "FactoryInterface", ")", "{", "return", "$", "this", "->", "container", ";", "}", "return", "$", "this", "->", "container"...
Get ODM specific factory. @return FactoryInterface
[ "Get", "ODM", "specific", "factory", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/ORM.php#L429-L436
train
robertlemke/RobertLemke.Plugin.Blog
Classes/Controller/CommentController.php
CommentController.createAction
public function createAction(NodeInterface $postNode, NodeTemplate $newComment) { # Workaround until we can validate node templates properly: if (strlen($newComment->getProperty('author')) < 2) { $this->throwStatus(400, 'Your comment was NOT created - please specify your name.'); } if (filter_var($newComment->getProperty('emailAddress'), FILTER_VALIDATE_EMAIL) === false) { $this->throwStatus(400, 'Your comment was NOT created - you must specify a valid email address.'); } if (strlen($newComment->getProperty('text')) < 5) { $this->throwStatus(400, 'Your comment was NOT created - it was too short.'); } $newComment->setProperty('text', filter_var($newComment->getProperty('text'), FILTER_SANITIZE_STRIPPED)); $newComment->setProperty('author', filter_var($newComment->getProperty('author'), FILTER_SANITIZE_STRIPPED)); $newComment->setProperty('emailAddress', filter_var($newComment->getProperty('emailAddress'), FILTER_SANITIZE_STRIPPED)); $commentNode = $postNode->getNode('comments')->createNodeFromTemplate($newComment, uniqid('comment-')); $commentNode->setProperty('spam', false); $commentNode->setProperty('datePublished', new \DateTime()); if ($this->akismetService->isCommentSpam('', $commentNode->getProperty('text'), 'comment', $commentNode->getProperty('author'), $commentNode->getProperty('emailAddress'))) { $commentNode->setProperty('spam', true); } $this->emitCommentCreated($commentNode, $postNode); $this->response->setStatus(201); return 'Thank you for your comment!'; }
php
public function createAction(NodeInterface $postNode, NodeTemplate $newComment) { # Workaround until we can validate node templates properly: if (strlen($newComment->getProperty('author')) < 2) { $this->throwStatus(400, 'Your comment was NOT created - please specify your name.'); } if (filter_var($newComment->getProperty('emailAddress'), FILTER_VALIDATE_EMAIL) === false) { $this->throwStatus(400, 'Your comment was NOT created - you must specify a valid email address.'); } if (strlen($newComment->getProperty('text')) < 5) { $this->throwStatus(400, 'Your comment was NOT created - it was too short.'); } $newComment->setProperty('text', filter_var($newComment->getProperty('text'), FILTER_SANITIZE_STRIPPED)); $newComment->setProperty('author', filter_var($newComment->getProperty('author'), FILTER_SANITIZE_STRIPPED)); $newComment->setProperty('emailAddress', filter_var($newComment->getProperty('emailAddress'), FILTER_SANITIZE_STRIPPED)); $commentNode = $postNode->getNode('comments')->createNodeFromTemplate($newComment, uniqid('comment-')); $commentNode->setProperty('spam', false); $commentNode->setProperty('datePublished', new \DateTime()); if ($this->akismetService->isCommentSpam('', $commentNode->getProperty('text'), 'comment', $commentNode->getProperty('author'), $commentNode->getProperty('emailAddress'))) { $commentNode->setProperty('spam', true); } $this->emitCommentCreated($commentNode, $postNode); $this->response->setStatus(201); return 'Thank you for your comment!'; }
[ "public", "function", "createAction", "(", "NodeInterface", "$", "postNode", ",", "NodeTemplate", "$", "newComment", ")", "{", "# Workaround until we can validate node templates properly:", "if", "(", "strlen", "(", "$", "newComment", "->", "getProperty", "(", "'author'...
Creates a new comment @param NodeInterface $postNode The post node which will contain the new comment @param NodeTemplate<RobertLemke.Plugin.Blog:Comment> $newComment @return string
[ "Creates", "a", "new", "comment" ]
7780d7e37022056ebe31088c7917ecaad8881dde
https://github.com/robertlemke/RobertLemke.Plugin.Blog/blob/7780d7e37022056ebe31088c7917ecaad8881dde/Classes/Controller/CommentController.php#L48-L79
train
spiral/orm
source/Spiral/ORM/Entities/Relations/AbstractRelation.php
AbstractRelation.primaryColumnOf
protected function primaryColumnOf(RecordInterface $record): string { return $this->orm->define(get_class($record), ORMInterface::R_PRIMARY_KEY); }
php
protected function primaryColumnOf(RecordInterface $record): string { return $this->orm->define(get_class($record), ORMInterface::R_PRIMARY_KEY); }
[ "protected", "function", "primaryColumnOf", "(", "RecordInterface", "$", "record", ")", ":", "string", "{", "return", "$", "this", "->", "orm", "->", "define", "(", "get_class", "(", "$", "record", ")", ",", "ORMInterface", "::", "R_PRIMARY_KEY", ")", ";", ...
Get primary key column @param RecordInterface $record @return string
[ "Get", "primary", "key", "column" ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/AbstractRelation.php#L140-L143
train
spiral/orm
source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php
ManyToManyRelation.getPivot
public function getPivot(RecordInterface $record): array { if (empty($matched = $this->matchOne($record))) { return []; } return $this->pivotData->offsetGet($matched); }
php
public function getPivot(RecordInterface $record): array { if (empty($matched = $this->matchOne($record))) { return []; } return $this->pivotData->offsetGet($matched); }
[ "public", "function", "getPivot", "(", "RecordInterface", "$", "record", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "matched", "=", "$", "this", "->", "matchOne", "(", "$", "record", ")", ")", ")", "{", "return", "[", "]", ";", "}", "ret...
Get pivot data associated with specific instance. @param RecordInterface $record @return array
[ "Get", "pivot", "data", "associated", "with", "specific", "instance", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php#L150-L157
train
spiral/orm
source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php
ManyToManyRelation.link
public function link(RecordInterface $record, array $pivotData = []): self { $this->loadData(true); $this->assertValid($record); $this->assertPivot($pivotData); //Ensure reference $record = $this->matchOne($record) ?? $record; if (in_array($record, $this->instances, true)) { //Merging pivot data $this->pivotData->offsetSet($record, $pivotData + $this->getPivot($record)); if (!in_array($record, $this->updated, true) && !in_array($record, $this->scheduled, true)) { //Indicating that record pivot data has been changed $this->updated[] = $record; } return $this; } //New association $this->instances[] = $record; $this->scheduled[] = $record; $this->pivotData->offsetSet($record, $pivotData); return $this; }
php
public function link(RecordInterface $record, array $pivotData = []): self { $this->loadData(true); $this->assertValid($record); $this->assertPivot($pivotData); //Ensure reference $record = $this->matchOne($record) ?? $record; if (in_array($record, $this->instances, true)) { //Merging pivot data $this->pivotData->offsetSet($record, $pivotData + $this->getPivot($record)); if (!in_array($record, $this->updated, true) && !in_array($record, $this->scheduled, true)) { //Indicating that record pivot data has been changed $this->updated[] = $record; } return $this; } //New association $this->instances[] = $record; $this->scheduled[] = $record; $this->pivotData->offsetSet($record, $pivotData); return $this; }
[ "public", "function", "link", "(", "RecordInterface", "$", "record", ",", "array", "$", "pivotData", "=", "[", "]", ")", ":", "self", "{", "$", "this", "->", "loadData", "(", "true", ")", ";", "$", "this", "->", "assertValid", "(", "$", "record", ")"...
Link record with parent entity. Only record instances is accepted. Attention, attached instances MIGHT be de-referenced IF parent object was reselected in a different scope. @param RecordInterface $record @param array $pivotData @return self @throws RelationException
[ "Link", "record", "with", "parent", "entity", ".", "Only", "record", "instances", "is", "accepted", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php#L172-L199
train
spiral/orm
source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php
ManyToManyRelation.unlink
public function unlink(RecordInterface $record): self { $this->loadData(true); //Ensure reference $record = $this->matchOne($record) ?? $record; foreach ($this->instances as $index => $linked) { if ($this->match($linked, $record)) { //Removing locally unset($this->instances[$index]); if (!in_array($linked, $this->scheduled, true) || !$this->autoload) { //Scheduling unlink in db when we know relation OR partial mode is on $this->unlinked[] = $linked; } break; } } $this->instances = array_values($this->instances); return $this; }
php
public function unlink(RecordInterface $record): self { $this->loadData(true); //Ensure reference $record = $this->matchOne($record) ?? $record; foreach ($this->instances as $index => $linked) { if ($this->match($linked, $record)) { //Removing locally unset($this->instances[$index]); if (!in_array($linked, $this->scheduled, true) || !$this->autoload) { //Scheduling unlink in db when we know relation OR partial mode is on $this->unlinked[] = $linked; } break; } } $this->instances = array_values($this->instances); return $this; }
[ "public", "function", "unlink", "(", "RecordInterface", "$", "record", ")", ":", "self", "{", "$", "this", "->", "loadData", "(", "true", ")", ";", "//Ensure reference", "$", "record", "=", "$", "this", "->", "matchOne", "(", "$", "record", ")", "??", ...
Unlink specific entity from relation. Will load relation data! Record to delete will be automatically matched to a give record. @param RecordInterface $record @return self @throws RelationException When entity not linked.
[ "Unlink", "specific", "entity", "from", "relation", ".", "Will", "load", "relation", "data!", "Record", "to", "delete", "will", "be", "automatically", "matched", "to", "a", "give", "record", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php#L211-L234
train
spiral/orm
source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php
ManyToManyRelation.loadRelated
protected function loadRelated(): array { $innerKey = $this->parent->getField($this->key(Record::INNER_KEY)); if (empty($innerKey)) { return []; } //Work with pre-build query $query = $this->createQuery($innerKey); //Use custom node to parse data $node = new PivotedRootNode( $this->schema[Record::RELATION_COLUMNS], $this->schema[Record::PIVOT_COLUMNS], $this->schema[Record::OUTER_KEY], $this->schema[Record::THOUGHT_INNER_KEY], $this->schema[Record::THOUGHT_OUTER_KEY] ); $iterator = $query->getIterator(); foreach ($iterator as $row) { //Time to parse some data $node->parseRow(0, $row); } //Memory free $iterator->close(); return $node->getResult(); }
php
protected function loadRelated(): array { $innerKey = $this->parent->getField($this->key(Record::INNER_KEY)); if (empty($innerKey)) { return []; } //Work with pre-build query $query = $this->createQuery($innerKey); //Use custom node to parse data $node = new PivotedRootNode( $this->schema[Record::RELATION_COLUMNS], $this->schema[Record::PIVOT_COLUMNS], $this->schema[Record::OUTER_KEY], $this->schema[Record::THOUGHT_INNER_KEY], $this->schema[Record::THOUGHT_OUTER_KEY] ); $iterator = $query->getIterator(); foreach ($iterator as $row) { //Time to parse some data $node->parseRow(0, $row); } //Memory free $iterator->close(); return $node->getResult(); }
[ "protected", "function", "loadRelated", "(", ")", ":", "array", "{", "$", "innerKey", "=", "$", "this", "->", "parent", "->", "getField", "(", "$", "this", "->", "key", "(", "Record", "::", "INNER_KEY", ")", ")", ";", "if", "(", "empty", "(", "$", ...
Fetch data from database. Lazy load. Method require a bit of love. @return array
[ "Fetch", "data", "from", "database", ".", "Lazy", "load", ".", "Method", "require", "a", "bit", "of", "love", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php#L372-L401
train
spiral/orm
source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php
ManyToManyRelation.createQuery
protected function createQuery($innerKey): SelectQuery { $table = $this->orm->table($this->class); $query = $table->select(); //Loader will take care of query configuration $loader = new ManyToManyLoader( $this->class, $table->getName(), $this->schema, $this->orm, $this->targetRole() ); //This is root loader, we can do self-alias (THIS IS SAFE due loader in POSTLOAD mode) $loader = $loader->withContext( $loader, [ 'alias' => $table->getName(), 'pivotAlias' => $table->getName() . '_pivot', 'method' => RelationLoader::POSTLOAD ] ); //Configuring query using parent inner key value as reference /** @var ManyToManyLoader $loader */ $query = $loader->configureQuery($query, true, [$innerKey]); //Additional pivot conditions $pivotDecorator = new AliasDecorator($query, 'onWhere', $table->getName() . '_pivot'); $pivotDecorator->where($this->schema[Record::WHERE_PIVOT]); $decorator = new AliasDecorator($query, 'where', 'root'); //Additional where conditions! if (!empty($this->schema[Record::WHERE])) { $decorator->where($this->schema[Record::WHERE]); } if (!empty($this->schema[Record::ORDER_BY])) { //Sorting $decorator->orderBy((array)$this->schema[Record::ORDER_BY]); } return $query; }
php
protected function createQuery($innerKey): SelectQuery { $table = $this->orm->table($this->class); $query = $table->select(); //Loader will take care of query configuration $loader = new ManyToManyLoader( $this->class, $table->getName(), $this->schema, $this->orm, $this->targetRole() ); //This is root loader, we can do self-alias (THIS IS SAFE due loader in POSTLOAD mode) $loader = $loader->withContext( $loader, [ 'alias' => $table->getName(), 'pivotAlias' => $table->getName() . '_pivot', 'method' => RelationLoader::POSTLOAD ] ); //Configuring query using parent inner key value as reference /** @var ManyToManyLoader $loader */ $query = $loader->configureQuery($query, true, [$innerKey]); //Additional pivot conditions $pivotDecorator = new AliasDecorator($query, 'onWhere', $table->getName() . '_pivot'); $pivotDecorator->where($this->schema[Record::WHERE_PIVOT]); $decorator = new AliasDecorator($query, 'where', 'root'); //Additional where conditions! if (!empty($this->schema[Record::WHERE])) { $decorator->where($this->schema[Record::WHERE]); } if (!empty($this->schema[Record::ORDER_BY])) { //Sorting $decorator->orderBy((array)$this->schema[Record::ORDER_BY]); } return $query; }
[ "protected", "function", "createQuery", "(", "$", "innerKey", ")", ":", "SelectQuery", "{", "$", "table", "=", "$", "this", "->", "orm", "->", "table", "(", "$", "this", "->", "class", ")", ";", "$", "query", "=", "$", "table", "->", "select", "(", ...
Create query for lazy loading. @param mixed $innerKey @return SelectQuery
[ "Create", "query", "for", "lazy", "loading", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php#L410-L455
train
spiral/orm
source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php
ManyToManyRelation.initInstances
protected function initInstances(): MultipleRelation { if (is_array($this->data) && !empty($this->data)) { //Iterates and instantiate records $iterator = new RecordIterator($this->data, $this->class, $this->orm); foreach ($iterator as $pivotData => $item) { if (in_array($item, $this->instances, true)) { //Skip duplicates (if any?) continue; } $this->pivotData->attach($item, $pivotData); $this->instances[] = $item; } } //Memory free $this->data = []; return $this; }
php
protected function initInstances(): MultipleRelation { if (is_array($this->data) && !empty($this->data)) { //Iterates and instantiate records $iterator = new RecordIterator($this->data, $this->class, $this->orm); foreach ($iterator as $pivotData => $item) { if (in_array($item, $this->instances, true)) { //Skip duplicates (if any?) continue; } $this->pivotData->attach($item, $pivotData); $this->instances[] = $item; } } //Memory free $this->data = []; return $this; }
[ "protected", "function", "initInstances", "(", ")", ":", "MultipleRelation", "{", "if", "(", "is_array", "(", "$", "this", "->", "data", ")", "&&", "!", "empty", "(", "$", "this", "->", "data", ")", ")", "{", "//Iterates and instantiate records", "$", "ite...
Init relations and populate pivot map. @return self|MultipleRelation
[ "Init", "relations", "and", "populate", "pivot", "map", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php#L462-L483
train
spiral/orm
source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php
ManyToManyRelation.assertPivot
private function assertPivot(array $pivotData) { if ($diff = array_diff(array_keys($pivotData), $this->schema[Record::PIVOT_COLUMNS])) { throw new RelationException( "Invalid pivot data, undefined columns found: " . join(', ', $diff) ); } }
php
private function assertPivot(array $pivotData) { if ($diff = array_diff(array_keys($pivotData), $this->schema[Record::PIVOT_COLUMNS])) { throw new RelationException( "Invalid pivot data, undefined columns found: " . join(', ', $diff) ); } }
[ "private", "function", "assertPivot", "(", "array", "$", "pivotData", ")", "{", "if", "(", "$", "diff", "=", "array_diff", "(", "array_keys", "(", "$", "pivotData", ")", ",", "$", "this", "->", "schema", "[", "Record", "::", "PIVOT_COLUMNS", "]", ")", ...
Make sure that pivot data in a valid format. @param array $pivotData @throws RelationException
[ "Make", "sure", "that", "pivot", "data", "in", "a", "valid", "format", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php#L508-L515
train
spiral/orm
source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php
ManyToManyRelation.targetRole
private function targetRole(): string { return $this->targetRole ?? $this->orm->define( get_class($this->parent), ORMInterface::R_ROLE_NAME ); }
php
private function targetRole(): string { return $this->targetRole ?? $this->orm->define( get_class($this->parent), ORMInterface::R_ROLE_NAME ); }
[ "private", "function", "targetRole", "(", ")", ":", "string", "{", "return", "$", "this", "->", "targetRole", "??", "$", "this", "->", "orm", "->", "define", "(", "get_class", "(", "$", "this", "->", "parent", ")", ",", "ORMInterface", "::", "R_ROLE_NAME...
Defined role to be used in morphed relations. @return string
[ "Defined", "role", "to", "be", "used", "in", "morphed", "relations", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/Relations/ManyToManyRelation.php#L522-L528
train
spiral/orm
source/Spiral/ORM/Transaction.php
Transaction.getCommands
public function getCommands() { foreach ($this->commands as $command) { if ($command instanceof \Traversable) { //Nested commands yield from $command; } yield $command; } }
php
public function getCommands() { foreach ($this->commands as $command) { if ($command instanceof \Traversable) { //Nested commands yield from $command; } yield $command; } }
[ "public", "function", "getCommands", "(", ")", "{", "foreach", "(", "$", "this", "->", "commands", "as", "$", "command", ")", "{", "if", "(", "$", "command", "instanceof", "\\", "Traversable", ")", "{", "//Nested commands", "yield", "from", "$", "command",...
Will return flattened list of commands. @return \Generator
[ "Will", "return", "flattened", "list", "of", "commands", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Transaction.php#L68-L78
train
rinvex/cortex-foundation
src/Providers/FoundationServiceProvider.php
FoundationServiceProvider.overrideNotificationMiddleware
protected function overrideNotificationMiddleware(): void { $this->app->singleton('Cortex\Foundation\Http\Middleware\NotificationMiddleware', function ($app) { return new NotificationMiddleware( $app['session.store'], $app['notification'], $app['config']->get('notification.session_key') ); }); }
php
protected function overrideNotificationMiddleware(): void { $this->app->singleton('Cortex\Foundation\Http\Middleware\NotificationMiddleware', function ($app) { return new NotificationMiddleware( $app['session.store'], $app['notification'], $app['config']->get('notification.session_key') ); }); }
[ "protected", "function", "overrideNotificationMiddleware", "(", ")", ":", "void", "{", "$", "this", "->", "app", "->", "singleton", "(", "'Cortex\\Foundation\\Http\\Middleware\\NotificationMiddleware'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "N...
Override notification middleware. @return void
[ "Override", "notification", "middleware", "." ]
230c100d98131c76f777e5036b3e7cd83af49e6e
https://github.com/rinvex/cortex-foundation/blob/230c100d98131c76f777e5036b3e7cd83af49e6e/src/Providers/FoundationServiceProvider.php#L163-L172
train
rinvex/cortex-foundation
src/Providers/FoundationServiceProvider.php
FoundationServiceProvider.bindBladeCompiler
protected function bindBladeCompiler(): void { $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) { // @alerts('container') $bladeCompiler->directive('alerts', function ($container = null) { if (strcasecmp('()', $container) === 0) { $container = null; } return "<?php echo app('notification')->container({$container})->show(); ?>"; }); }); }
php
protected function bindBladeCompiler(): void { $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) { // @alerts('container') $bladeCompiler->directive('alerts', function ($container = null) { if (strcasecmp('()', $container) === 0) { $container = null; } return "<?php echo app('notification')->container({$container})->show(); ?>"; }); }); }
[ "protected", "function", "bindBladeCompiler", "(", ")", ":", "void", "{", "$", "this", "->", "app", "->", "afterResolving", "(", "'blade.compiler'", ",", "function", "(", "BladeCompiler", "$", "bladeCompiler", ")", "{", "// @alerts('container')", "$", "bladeCompil...
Bind blade compiler. @return void
[ "Bind", "blade", "compiler", "." ]
230c100d98131c76f777e5036b3e7cd83af49e6e
https://github.com/rinvex/cortex-foundation/blob/230c100d98131c76f777e5036b3e7cd83af49e6e/src/Providers/FoundationServiceProvider.php#L179-L192
train
rinvex/cortex-foundation
src/Providers/FoundationServiceProvider.php
FoundationServiceProvider.overrideRedirector
protected function overrideRedirector(): void { $this->app->singleton('redirect', function ($app) { $redirector = new Redirector($app['url']); // If the session is set on the application instance, we'll inject it into // the redirector instance. This allows the redirect responses to allow // for the quite convenient "with" methods that flash to the session. if (isset($app['session.store'])) { $redirector->setSession($app['session.store']); } return $redirector; }); }
php
protected function overrideRedirector(): void { $this->app->singleton('redirect', function ($app) { $redirector = new Redirector($app['url']); // If the session is set on the application instance, we'll inject it into // the redirector instance. This allows the redirect responses to allow // for the quite convenient "with" methods that flash to the session. if (isset($app['session.store'])) { $redirector->setSession($app['session.store']); } return $redirector; }); }
[ "protected", "function", "overrideRedirector", "(", ")", ":", "void", "{", "$", "this", "->", "app", "->", "singleton", "(", "'redirect'", ",", "function", "(", "$", "app", ")", "{", "$", "redirector", "=", "new", "Redirector", "(", "$", "app", "[", "'...
Override the Redirector instance. @return void
[ "Override", "the", "Redirector", "instance", "." ]
230c100d98131c76f777e5036b3e7cd83af49e6e
https://github.com/rinvex/cortex-foundation/blob/230c100d98131c76f777e5036b3e7cd83af49e6e/src/Providers/FoundationServiceProvider.php#L199-L213
train
rinvex/cortex-foundation
src/Providers/FoundationServiceProvider.php
FoundationServiceProvider.overrideUrlGenerator
protected function overrideUrlGenerator(): void { $this->app->singleton('url', function ($app) { $routes = $app['router']->getRoutes(); // The URL generator needs the route collection that exists on the router. // Keep in mind this is an object, so we're passing by references here // and all the registered routes will be available to the generator. $app->instance('routes', $routes); $url = new UrlGenerator( $routes, $app->rebinding( 'request', $this->requestRebinder() ) ); $url->setSessionResolver(function () { return $this->app['session']; }); // If the route collection is "rebound", for example, when the routes stay // cached for the application, we will need to rebind the routes on the // URL generator instance so it has the latest version of the routes. $app->rebinding('routes', function ($app, $routes) { $app['url']->setRoutes($routes); }); return $url; }); }
php
protected function overrideUrlGenerator(): void { $this->app->singleton('url', function ($app) { $routes = $app['router']->getRoutes(); // The URL generator needs the route collection that exists on the router. // Keep in mind this is an object, so we're passing by references here // and all the registered routes will be available to the generator. $app->instance('routes', $routes); $url = new UrlGenerator( $routes, $app->rebinding( 'request', $this->requestRebinder() ) ); $url->setSessionResolver(function () { return $this->app['session']; }); // If the route collection is "rebound", for example, when the routes stay // cached for the application, we will need to rebind the routes on the // URL generator instance so it has the latest version of the routes. $app->rebinding('routes', function ($app, $routes) { $app['url']->setRoutes($routes); }); return $url; }); }
[ "protected", "function", "overrideUrlGenerator", "(", ")", ":", "void", "{", "$", "this", "->", "app", "->", "singleton", "(", "'url'", ",", "function", "(", "$", "app", ")", "{", "$", "routes", "=", "$", "app", "[", "'router'", "]", "->", "getRoutes",...
Override the UrlGenerator instance. @return void
[ "Override", "the", "UrlGenerator", "instance", "." ]
230c100d98131c76f777e5036b3e7cd83af49e6e
https://github.com/rinvex/cortex-foundation/blob/230c100d98131c76f777e5036b3e7cd83af49e6e/src/Providers/FoundationServiceProvider.php#L220-L249
train
rinvex/cortex-foundation
src/Providers/FoundationServiceProvider.php
FoundationServiceProvider.bindPresenceVerifier
protected function bindPresenceVerifier(): void { $this->app->bind('cortex.foundation.presence.verifier', function ($app) { return new EloquentPresenceVerifier($app['db'], new $app[AbstractModel::class]()); }); }
php
protected function bindPresenceVerifier(): void { $this->app->bind('cortex.foundation.presence.verifier', function ($app) { return new EloquentPresenceVerifier($app['db'], new $app[AbstractModel::class]()); }); }
[ "protected", "function", "bindPresenceVerifier", "(", ")", ":", "void", "{", "$", "this", "->", "app", "->", "bind", "(", "'cortex.foundation.presence.verifier'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "EloquentPresenceVerifier", "(", "$", ...
Bind presence verifier. @return void
[ "Bind", "presence", "verifier", "." ]
230c100d98131c76f777e5036b3e7cd83af49e6e
https://github.com/rinvex/cortex-foundation/blob/230c100d98131c76f777e5036b3e7cd83af49e6e/src/Providers/FoundationServiceProvider.php#L337-L342
train
rinvex/cortex-foundation
src/Providers/FoundationServiceProvider.php
FoundationServiceProvider.bindBlueprintMacro
protected function bindBlueprintMacro(): void { Blueprint::macro('auditable', function () { $this->integer('created_by_id')->unsigned()->after('created_at')->nullable(); $this->string('created_by_type')->after('created_at')->nullable(); $this->integer('updated_by_id')->unsigned()->after('updated_at')->nullable(); $this->string('updated_by_type')->after('updated_at')->nullable(); }); Blueprint::macro('dropAuditable', function () { $this->dropForeign($this->createIndexName('foreign', ['updated_by_type'])); $this->dropForeign($this->createIndexName('foreign', ['updated_by_id'])); $this->dropForeign($this->createIndexName('foreign', ['created_by_type'])); $this->dropForeign($this->createIndexName('foreign', ['created_by_id'])); $this->dropColumn(['updated_by_type', 'updated_by_id', 'created_by_type', 'created_by_id']); }); Blueprint::macro('auditableAndTimestamps', function ($precision = 0) { $this->timestamp('created_at', $precision)->nullable(); $this->integer('created_by_id')->unsigned()->nullable(); $this->string('created_by_type')->nullable(); $this->timestamp('updated_at', $precision)->nullable(); $this->integer('updated_by_id')->unsigned()->nullable(); $this->string('updated_by_type')->nullable(); }); Blueprint::macro('dropauditableAndTimestamps', function () { $this->dropForeign($this->createIndexName('foreign', ['updated_by_type'])); $this->dropForeign($this->createIndexName('foreign', ['updated_by_id'])); $this->dropForeign($this->createIndexName('foreign', ['updated_at'])); $this->dropForeign($this->createIndexName('foreign', ['created_by_type'])); $this->dropForeign($this->createIndexName('foreign', ['created_by_id'])); $this->dropForeign($this->createIndexName('foreign', ['created_at'])); $this->dropColumn(['updated_by_type', 'updated_by_id', 'updated_at', 'created_by_type', 'created_by_id', 'created_at']); }); }
php
protected function bindBlueprintMacro(): void { Blueprint::macro('auditable', function () { $this->integer('created_by_id')->unsigned()->after('created_at')->nullable(); $this->string('created_by_type')->after('created_at')->nullable(); $this->integer('updated_by_id')->unsigned()->after('updated_at')->nullable(); $this->string('updated_by_type')->after('updated_at')->nullable(); }); Blueprint::macro('dropAuditable', function () { $this->dropForeign($this->createIndexName('foreign', ['updated_by_type'])); $this->dropForeign($this->createIndexName('foreign', ['updated_by_id'])); $this->dropForeign($this->createIndexName('foreign', ['created_by_type'])); $this->dropForeign($this->createIndexName('foreign', ['created_by_id'])); $this->dropColumn(['updated_by_type', 'updated_by_id', 'created_by_type', 'created_by_id']); }); Blueprint::macro('auditableAndTimestamps', function ($precision = 0) { $this->timestamp('created_at', $precision)->nullable(); $this->integer('created_by_id')->unsigned()->nullable(); $this->string('created_by_type')->nullable(); $this->timestamp('updated_at', $precision)->nullable(); $this->integer('updated_by_id')->unsigned()->nullable(); $this->string('updated_by_type')->nullable(); }); Blueprint::macro('dropauditableAndTimestamps', function () { $this->dropForeign($this->createIndexName('foreign', ['updated_by_type'])); $this->dropForeign($this->createIndexName('foreign', ['updated_by_id'])); $this->dropForeign($this->createIndexName('foreign', ['updated_at'])); $this->dropForeign($this->createIndexName('foreign', ['created_by_type'])); $this->dropForeign($this->createIndexName('foreign', ['created_by_id'])); $this->dropForeign($this->createIndexName('foreign', ['created_at'])); $this->dropColumn(['updated_by_type', 'updated_by_id', 'updated_at', 'created_by_type', 'created_by_id', 'created_at']); }); }
[ "protected", "function", "bindBlueprintMacro", "(", ")", ":", "void", "{", "Blueprint", "::", "macro", "(", "'auditable'", ",", "function", "(", ")", "{", "$", "this", "->", "integer", "(", "'created_by_id'", ")", "->", "unsigned", "(", ")", "->", "after",...
Bind blueprint macro. @return void
[ "Bind", "blueprint", "macro", "." ]
230c100d98131c76f777e5036b3e7cd83af49e6e
https://github.com/rinvex/cortex-foundation/blob/230c100d98131c76f777e5036b3e7cd83af49e6e/src/Providers/FoundationServiceProvider.php#L349-L384
train
rinvex/cortex-foundation
src/Console/Commands/DataTableMakeCommand.php
DataTableMakeCommand.replaceClasses
protected function replaceClasses($stub, $model, $transformer = null): string { if ($transformer) { $transformer = str_replace('/', '\\', $transformer); $namespaceTransformer = $this->rootNamespace().'\Transformers\\'.$transformer; if (starts_with($transformer, '\\')) { $stub = str_replace('NamespacedDummyTransformer', trim($transformer, '\\'), $stub); } else { $stub = str_replace('NamespacedDummyTransformer', $namespaceTransformer, $stub); } $stub = str_replace( "use {$namespaceTransformer};\nuse {$namespaceTransformer};", "use {$namespaceTransformer};", $stub ); $transformer = class_basename(trim($transformer, '\\')); $stub = str_replace('DummyTransformer', $transformer, $stub); $stub = str_replace('dummyTransformer', camel_case($transformer), $stub); } $model = str_replace('/', '\\', $model); $namespaceModel = $this->rootNamespace().'\Models\\'.$model; if (starts_with($model, '\\')) { $stub = str_replace('NamespacedDummyModel', trim($model, '\\'), $stub); } else { $stub = str_replace('NamespacedDummyModel', $namespaceModel, $stub); } $stub = str_replace( "use {$namespaceModel};\nuse {$namespaceModel};", "use {$namespaceModel};", $stub ); $model = class_basename(trim($model, '\\')); $stub = str_replace('DummyModel', $model, $stub); return str_replace('dummyModel', camel_case($model), $stub); }
php
protected function replaceClasses($stub, $model, $transformer = null): string { if ($transformer) { $transformer = str_replace('/', '\\', $transformer); $namespaceTransformer = $this->rootNamespace().'\Transformers\\'.$transformer; if (starts_with($transformer, '\\')) { $stub = str_replace('NamespacedDummyTransformer', trim($transformer, '\\'), $stub); } else { $stub = str_replace('NamespacedDummyTransformer', $namespaceTransformer, $stub); } $stub = str_replace( "use {$namespaceTransformer};\nuse {$namespaceTransformer};", "use {$namespaceTransformer};", $stub ); $transformer = class_basename(trim($transformer, '\\')); $stub = str_replace('DummyTransformer', $transformer, $stub); $stub = str_replace('dummyTransformer', camel_case($transformer), $stub); } $model = str_replace('/', '\\', $model); $namespaceModel = $this->rootNamespace().'\Models\\'.$model; if (starts_with($model, '\\')) { $stub = str_replace('NamespacedDummyModel', trim($model, '\\'), $stub); } else { $stub = str_replace('NamespacedDummyModel', $namespaceModel, $stub); } $stub = str_replace( "use {$namespaceModel};\nuse {$namespaceModel};", "use {$namespaceModel};", $stub ); $model = class_basename(trim($model, '\\')); $stub = str_replace('DummyModel', $model, $stub); return str_replace('dummyModel', camel_case($model), $stub); }
[ "protected", "function", "replaceClasses", "(", "$", "stub", ",", "$", "model", ",", "$", "transformer", "=", "null", ")", ":", "string", "{", "if", "(", "$", "transformer", ")", "{", "$", "transformer", "=", "str_replace", "(", "'/'", ",", "'\\\\'", "...
Replace the model and transformer for the given stub. @param string $stub @param string $model @param string $transformer @return string
[ "Replace", "the", "model", "and", "transformer", "for", "the", "given", "stub", "." ]
230c100d98131c76f777e5036b3e7cd83af49e6e
https://github.com/rinvex/cortex-foundation/blob/230c100d98131c76f777e5036b3e7cd83af49e6e/src/Console/Commands/DataTableMakeCommand.php#L80-L123
train
spiral/orm
source/Spiral/ORM/Helpers/RelationOptions.php
RelationOptions.define
public function define(string $option) { if (!array_key_exists($option, $this->options)) { throw new OptionsException("Undefined relation option '{$option}'"); } return $this->options[$option]; }
php
public function define(string $option) { if (!array_key_exists($option, $this->options)) { throw new OptionsException("Undefined relation option '{$option}'"); } return $this->options[$option]; }
[ "public", "function", "define", "(", "string", "$", "option", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "option", ",", "$", "this", "->", "options", ")", ")", "{", "throw", "new", "OptionsException", "(", "\"Undefined relation option '{$option}'\...
Get value for a specific option. Attention, option MUST exist in template in order to be retrievable. @param string $option @return mixed @throws OptionsException
[ "Get", "value", "for", "a", "specific", "option", ".", "Attention", "option", "MUST", "exist", "in", "template", "in", "order", "to", "be", "retrievable", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Helpers/RelationOptions.php#L73-L80
train
spiral/orm
source/Spiral/ORM/Helpers/RelationOptions.php
RelationOptions.calculateOptions
protected function calculateOptions(array $userOptions): array { foreach ($this->template as $property => $pattern) { if (isset($userOptions[$property])) { //Specified by user continue; } if (!is_string($pattern)) { //Some options are actually array of options $userOptions[$property] = $pattern; continue; } //Let's create option value using default proposer values $userOptions[$property] = \Spiral\interpolate( $pattern, $this->proposedOptions($userOptions) ); } return $userOptions; }
php
protected function calculateOptions(array $userOptions): array { foreach ($this->template as $property => $pattern) { if (isset($userOptions[$property])) { //Specified by user continue; } if (!is_string($pattern)) { //Some options are actually array of options $userOptions[$property] = $pattern; continue; } //Let's create option value using default proposer values $userOptions[$property] = \Spiral\interpolate( $pattern, $this->proposedOptions($userOptions) ); } return $userOptions; }
[ "protected", "function", "calculateOptions", "(", "array", "$", "userOptions", ")", ":", "array", "{", "foreach", "(", "$", "this", "->", "template", "as", "$", "property", "=>", "$", "pattern", ")", "{", "if", "(", "isset", "(", "$", "userOptions", "[",...
Calculate options based on given template @param array $userOptions Options provided by user. @return array Calculated options.
[ "Calculate", "options", "based", "on", "given", "template" ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Helpers/RelationOptions.php#L101-L123
train
spiral/orm
source/Spiral/ORM/Helpers/RelationOptions.php
RelationOptions.proposedOptions
protected function proposedOptions(array $userOptions): array { $source = $this->definition->sourceContext(); $proposed = [ //Relation name 'relation:name' => $this->definition->getName(), //Relation name in plural form 'relation:plural' => Inflector::pluralize($this->definition->getName()), //Relation name in singular form 'relation:singular' => Inflector::singularize($this->definition->getName()), //Parent record role name 'source:role' => $source->getRole(), //Parent record table name 'source:table' => $source->getTable(), //Parent record primary key 'source:primaryKey' => $source->getPrimary()->getName(), ]; //Some options may use values declared in other definition fields $aliases = [ Record::OUTER_KEY => 'outerKey', Record::INNER_KEY => 'innerKey', Record::PIVOT_TABLE => 'pivotTable', ]; foreach ($aliases as $property => $alias) { if (isset($userOptions[$property])) { //Let's create some default options based on user specified values $proposed['option:' . $alias] = $userOptions[$property]; } } if (!empty($this->definition->targetContext())) { $target = $this->definition->targetContext(); $proposed = $proposed + [ //Outer role name 'target:role' => $target->getRole(), //Outer record table 'target:table' => $target->getTable(), //Outer record primary key 'target:primaryKey' => !empty($target->getPrimary()) ? $target->getPrimary()->getName() : '', ]; } return $proposed; }
php
protected function proposedOptions(array $userOptions): array { $source = $this->definition->sourceContext(); $proposed = [ //Relation name 'relation:name' => $this->definition->getName(), //Relation name in plural form 'relation:plural' => Inflector::pluralize($this->definition->getName()), //Relation name in singular form 'relation:singular' => Inflector::singularize($this->definition->getName()), //Parent record role name 'source:role' => $source->getRole(), //Parent record table name 'source:table' => $source->getTable(), //Parent record primary key 'source:primaryKey' => $source->getPrimary()->getName(), ]; //Some options may use values declared in other definition fields $aliases = [ Record::OUTER_KEY => 'outerKey', Record::INNER_KEY => 'innerKey', Record::PIVOT_TABLE => 'pivotTable', ]; foreach ($aliases as $property => $alias) { if (isset($userOptions[$property])) { //Let's create some default options based on user specified values $proposed['option:' . $alias] = $userOptions[$property]; } } if (!empty($this->definition->targetContext())) { $target = $this->definition->targetContext(); $proposed = $proposed + [ //Outer role name 'target:role' => $target->getRole(), //Outer record table 'target:table' => $target->getTable(), //Outer record primary key 'target:primaryKey' => !empty($target->getPrimary()) ? $target->getPrimary()->getName() : '', ]; } return $proposed; }
[ "protected", "function", "proposedOptions", "(", "array", "$", "userOptions", ")", ":", "array", "{", "$", "source", "=", "$", "this", "->", "definition", "->", "sourceContext", "(", ")", ";", "$", "proposed", "=", "[", "//Relation name", "'relation:name'", ...
Create set of options to specify missing relation definition fields. @param array $userOptions User options. @return array
[ "Create", "set", "of", "options", "to", "specify", "missing", "relation", "definition", "fields", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Helpers/RelationOptions.php#L132-L186
train
spiral/orm
source/Spiral/ORM/Entities/RecordSelector.php
RecordSelector.withColumns
public function withColumns(array $columns): self { $selector = clone $this; $selector->loader = $selector->loader->withColumns($columns); return $selector; }
php
public function withColumns(array $columns): self { $selector = clone $this; $selector->loader = $selector->loader->withColumns($columns); return $selector; }
[ "public", "function", "withColumns", "(", "array", "$", "columns", ")", ":", "self", "{", "$", "selector", "=", "clone", "$", "this", ";", "$", "selector", "->", "loader", "=", "$", "selector", "->", "loader", "->", "withColumns", "(", "$", "columns", ...
Columns to be selected, please note, primary will always be included, DO not include column aliases in here, aliases will be added automatically. Creates selector as response. @param array $columns @return RecordSelector
[ "Columns", "to", "be", "selected", "please", "note", "primary", "will", "always", "be", "included", "DO", "not", "include", "column", "aliases", "in", "here", "aliases", "will", "be", "added", "automatically", ".", "Creates", "selector", "as", "response", "." ...
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/RecordSelector.php#L122-L128
train
spiral/orm
source/Spiral/ORM/Entities/RecordSelector.php
RecordSelector.load
public function load($relation, array $options = []): self { if (is_array($relation)) { foreach ($relation as $name => $subOption) { if (is_string($subOption)) { //Array of relation names $this->load($subOption, $options); } else { //Multiple relations or relation with addition load options $this->load($name, $subOption + $options); } } return $this; } //We are requesting primary loaded to pre-load nested relation $this->loader->loadRelation($relation, $options); return $this; }
php
public function load($relation, array $options = []): self { if (is_array($relation)) { foreach ($relation as $name => $subOption) { if (is_string($subOption)) { //Array of relation names $this->load($subOption, $options); } else { //Multiple relations or relation with addition load options $this->load($name, $subOption + $options); } } return $this; } //We are requesting primary loaded to pre-load nested relation $this->loader->loadRelation($relation, $options); return $this; }
[ "public", "function", "load", "(", "$", "relation", ",", "array", "$", "options", "=", "[", "]", ")", ":", "self", "{", "if", "(", "is_array", "(", "$", "relation", ")", ")", "{", "foreach", "(", "$", "relation", "as", "$", "name", "=>", "$", "su...
Request primary selector loader to pre-load relation name. Any type of loader can be used for data preloading. ORM loaders by default will select the most efficient way to load related data which might include additional select query or left join. Loaded data will automatically pre-populate record relations. You can specify nested relations using "." separator. Examples: //Select users and load their comments (will cast 2 queries, HAS_MANY comments) User::find()->with('comments'); //You can load chain of relations - select user and load their comments and post related to //comment User::find()->with('comments.post'); //We can also specify custom where conditions on data loading, let's load only public comments. User::find()->load('comments', [ 'where' => ['{@}.status' => 'public'] ]); Please note using "{@}" column name, this placeholder is required to prevent collisions and it will be automatically replaced with valid table alias of pre-loaded comments table. //In case where your loaded relation is MANY_TO_MANY you can also specify pivot table conditions, //let's pre-load all approved user tags, we can use same placeholder for pivot table alias User::find()->load('tags', [ 'wherePivot' => ['{@}.approved' => true] ]); //In most of cases you don't need to worry about how data was loaded, using external query or //left join, however if you want to change such behaviour you can force load method to INLOAD User::find()->load('tags', [ 'method' => Loader::INLOAD, 'wherePivot' => ['{@}.approved' => true] ]); Attention, you will not be able to correctly paginate in this case and only ORM loaders support different loading types. You can specify multiple loaders using array as first argument. Example: User::find()->load(['posts', 'comments', 'profile']); Attention, consider disabling entity map if you want to use recursive loading (i.e. post.tags.posts), but first think why you even need recursive relation loading. @see with() @param string|array $relation @param array $options @return $this|RecordSelector
[ "Request", "primary", "selector", "loader", "to", "pre", "-", "load", "relation", "name", ".", "Any", "type", "of", "loader", "can", "be", "used", "for", "data", "preloading", ".", "ORM", "loaders", "by", "default", "will", "select", "the", "most", "effici...
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/RecordSelector.php#L189-L209
train
spiral/orm
source/Spiral/ORM/Entities/RecordSelector.php
RecordSelector.wherePK
public function wherePK($id): self { if (empty($this->loader->primaryKey())) { //This MUST never happen due ORM requires PK now for every entity throw new SelectorException("Unable to set wherePK condition, no proper PK were defined"); } //Adding condition to initial query $this->loader->initialQuery()->where([ //Must be already aliased $this->loader->primaryKey() => $id ]); return $this; }
php
public function wherePK($id): self { if (empty($this->loader->primaryKey())) { //This MUST never happen due ORM requires PK now for every entity throw new SelectorException("Unable to set wherePK condition, no proper PK were defined"); } //Adding condition to initial query $this->loader->initialQuery()->where([ //Must be already aliased $this->loader->primaryKey() => $id ]); return $this; }
[ "public", "function", "wherePK", "(", "$", "id", ")", ":", "self", "{", "if", "(", "empty", "(", "$", "this", "->", "loader", "->", "primaryKey", "(", ")", ")", ")", "{", "//This MUST never happen due ORM requires PK now for every entity", "throw", "new", "Sel...
Shortcut to where method to set AND condition for parent record primary key. @param string|int $id @return RecordSelector @throws SelectorException
[ "Shortcut", "to", "where", "method", "to", "set", "AND", "condition", "for", "parent", "record", "primary", "key", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/RecordSelector.php#L319-L333
train
spiral/orm
source/Spiral/ORM/Entities/RecordSelector.php
RecordSelector.findOne
public function findOne(array $query = null) { $data = (clone $this)->where($query)->fetchData(); if (empty($data[0])) { return null; } return $this->orm->make($this->class, $data[0], ORMInterface::STATE_LOADED, true); }
php
public function findOne(array $query = null) { $data = (clone $this)->where($query)->fetchData(); if (empty($data[0])) { return null; } return $this->orm->make($this->class, $data[0], ORMInterface::STATE_LOADED, true); }
[ "public", "function", "findOne", "(", "array", "$", "query", "=", "null", ")", "{", "$", "data", "=", "(", "clone", "$", "this", ")", "->", "where", "(", "$", "query", ")", "->", "fetchData", "(", ")", ";", "if", "(", "empty", "(", "$", "data", ...
Find one entity or return null. @param array|null $query @return EntityInterface|null
[ "Find", "one", "entity", "or", "return", "null", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/RecordSelector.php#L342-L351
train
spiral/orm
source/Spiral/ORM/Entities/RecordSelector.php
RecordSelector.fetchAll
public function fetchAll( string $cacheKey = '', $ttl = 0, CacheInterface $cache = null ): array { return iterator_to_array($this->getIterator($cacheKey, $ttl, $cache)); }
php
public function fetchAll( string $cacheKey = '', $ttl = 0, CacheInterface $cache = null ): array { return iterator_to_array($this->getIterator($cacheKey, $ttl, $cache)); }
[ "public", "function", "fetchAll", "(", "string", "$", "cacheKey", "=", "''", ",", "$", "ttl", "=", "0", ",", "CacheInterface", "$", "cache", "=", "null", ")", ":", "array", "{", "return", "iterator_to_array", "(", "$", "this", "->", "getIterator", "(", ...
Fetch all records in a form of array. @param string $cacheKey @param int|\DateInterval $ttl @param CacheInterface|null $cache Can be automatically resoled via ORM container scope. @return RecordInterface[]
[ "Fetch", "all", "records", "in", "a", "form", "of", "array", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/RecordSelector.php#L362-L368
train
spiral/orm
source/Spiral/ORM/Entities/RecordSelector.php
RecordSelector.count
public function count(string $column = null): int { if (is_null($column)) { if (!empty($this->loader->primaryKey())) { //@tuneyourserver solves the issue with counting on queries with joins. $column = "DISTINCT({$this->loader->primaryKey()})"; } else { $column = '*'; } } return $this->compiledQuery()->count($column); }
php
public function count(string $column = null): int { if (is_null($column)) { if (!empty($this->loader->primaryKey())) { //@tuneyourserver solves the issue with counting on queries with joins. $column = "DISTINCT({$this->loader->primaryKey()})"; } else { $column = '*'; } } return $this->compiledQuery()->count($column); }
[ "public", "function", "count", "(", "string", "$", "column", "=", "null", ")", ":", "int", "{", "if", "(", "is_null", "(", "$", "column", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "loader", "->", "primaryKey", "(", ")", ")",...
Attention, column will be quoted by driver! @param string|null $column When column is null DISTINCT(PK) will be generated. @return int
[ "Attention", "column", "will", "be", "quoted", "by", "driver!" ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/RecordSelector.php#L413-L425
train
spiral/orm
source/Spiral/ORM/Entities/RecordSelector.php
RecordSelector.fetchData
public function fetchData(OutputNode $node = null): array { /** @var OutputNode $node */ $node = $node ?? $this->loader->createNode(); //Working with parser defined by loader itself $this->loader->loadData($node); return $node->getResult(); }
php
public function fetchData(OutputNode $node = null): array { /** @var OutputNode $node */ $node = $node ?? $this->loader->createNode(); //Working with parser defined by loader itself $this->loader->loadData($node); return $node->getResult(); }
[ "public", "function", "fetchData", "(", "OutputNode", "$", "node", "=", "null", ")", ":", "array", "{", "/** @var OutputNode $node */", "$", "node", "=", "$", "node", "??", "$", "this", "->", "loader", "->", "createNode", "(", ")", ";", "//Working with parse...
Load data tree from databases and linked loaders in a form of array. @param OutputNode $node When empty node will be created automatically by root relation loader. @return array
[ "Load", "data", "tree", "from", "databases", "and", "linked", "loaders", "in", "a", "form", "of", "array", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Entities/RecordSelector.php#L465-L474
train
spiral/orm
source/Spiral/ORM/Configs/MutatorsConfig.php
MutatorsConfig.getMutators
public function getMutators(string $type): array { $type = $this->resolveAlias($type); $mutators = $this->config['mutators']; return isset($mutators[$type]) ? $mutators[$type] : []; }
php
public function getMutators(string $type): array { $type = $this->resolveAlias($type); $mutators = $this->config['mutators']; return isset($mutators[$type]) ? $mutators[$type] : []; }
[ "public", "function", "getMutators", "(", "string", "$", "type", ")", ":", "array", "{", "$", "type", "=", "$", "this", "->", "resolveAlias", "(", "$", "type", ")", ";", "$", "mutators", "=", "$", "this", "->", "config", "[", "'mutators'", "]", ";", ...
Get list of mutators associated with given field type. @param string $type @return array
[ "Get", "list", "of", "mutators", "associated", "with", "given", "field", "type", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Configs/MutatorsConfig.php#L41-L47
train
spiral/orm
source/Spiral/ORM/Helpers/ColumnRenderer.php
ColumnRenderer.renderColumns
public function renderColumns( array $fields, array $defaults, AbstractTable $table ): AbstractTable { foreach ($fields as $name => $definition) { $column = $table->column($name); //Declaring our column $this->declareColumn( $column, $definition, array_key_exists($name, $defaults), $defaults[$name] ?? null ); } return clone $table; }
php
public function renderColumns( array $fields, array $defaults, AbstractTable $table ): AbstractTable { foreach ($fields as $name => $definition) { $column = $table->column($name); //Declaring our column $this->declareColumn( $column, $definition, array_key_exists($name, $defaults), $defaults[$name] ?? null ); } return clone $table; }
[ "public", "function", "renderColumns", "(", "array", "$", "fields", ",", "array", "$", "defaults", ",", "AbstractTable", "$", "table", ")", ":", "AbstractTable", "{", "foreach", "(", "$", "fields", "as", "$", "name", "=>", "$", "definition", ")", "{", "$...
Render columns in table based on string definition. Example: renderColumns([ 'id' => 'primary', 'time' => 'datetime, nullable', 'status' => 'enum(active, disabled)' ], [ 'status' => 'active', 'time' => null, //idential as if define column as null ], $table); Attention, new table instance will be returned! @param array $fields @param array $defaults @param AbstractTable $table @return AbstractTable @throws ColumnRenderException
[ "Render", "columns", "in", "table", "based", "on", "string", "definition", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Helpers/ColumnRenderer.php#L48-L66
train
spiral/orm
source/Spiral/ORM/Helpers/ColumnRenderer.php
ColumnRenderer.castDefault
public function castDefault(AbstractColumn $column) { if (in_array($column->abstractType(), ['timestamp', 'datetime', 'time', 'date'])) { return 0; } if ($column->abstractType() == 'enum') { //We can use first enum value as default return $column->getEnumValues()[0]; } switch ($column->phpType()) { case 'int': return 0; case 'float': return 0.0; case 'bool': return false; } return ''; }
php
public function castDefault(AbstractColumn $column) { if (in_array($column->abstractType(), ['timestamp', 'datetime', 'time', 'date'])) { return 0; } if ($column->abstractType() == 'enum') { //We can use first enum value as default return $column->getEnumValues()[0]; } switch ($column->phpType()) { case 'int': return 0; case 'float': return 0.0; case 'bool': return false; } return ''; }
[ "public", "function", "castDefault", "(", "AbstractColumn", "$", "column", ")", "{", "if", "(", "in_array", "(", "$", "column", "->", "abstractType", "(", ")", ",", "[", "'timestamp'", ",", "'datetime'", ",", "'time'", ",", "'date'", "]", ")", ")", "{", ...
Cast default value based on column type. Required to prevent conflicts when not nullable column added to existed table with data in. @param AbstractColumn $column @return mixed
[ "Cast", "default", "value", "based", "on", "column", "type", ".", "Required", "to", "prevent", "conflicts", "when", "not", "nullable", "column", "added", "to", "existed", "table", "with", "data", "in", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Helpers/ColumnRenderer.php#L177-L198
train
spiral/orm
source/Spiral/ORM/Schemas/SchemaBuilder.php
SchemaBuilder.addSchema
public function addSchema(SchemaInterface $schema): SchemaBuilder { $this->schemas[$schema->getClass()] = $schema; return $this; }
php
public function addSchema(SchemaInterface $schema): SchemaBuilder { $this->schemas[$schema->getClass()] = $schema; return $this; }
[ "public", "function", "addSchema", "(", "SchemaInterface", "$", "schema", ")", ":", "SchemaBuilder", "{", "$", "this", "->", "schemas", "[", "$", "schema", "->", "getClass", "(", ")", "]", "=", "$", "schema", ";", "return", "$", "this", ";", "}" ]
Add new model schema into pool. @param SchemaInterface $schema @return self|$this
[ "Add", "new", "model", "schema", "into", "pool", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Schemas/SchemaBuilder.php#L69-L74
train
spiral/orm
source/Spiral/ORM/Schemas/SchemaBuilder.php
SchemaBuilder.hasChanges
public function hasChanges(): bool { foreach ($this->getTables() as $table) { if ($table->getComparator()->hasChanges()) { return true; } } return false; }
php
public function hasChanges(): bool { foreach ($this->getTables() as $table) { if ($table->getComparator()->hasChanges()) { return true; } } return false; }
[ "public", "function", "hasChanges", "(", ")", ":", "bool", "{", "foreach", "(", "$", "this", "->", "getTables", "(", ")", "as", "$", "table", ")", "{", "if", "(", "$", "table", "->", "getComparator", "(", ")", "->", "hasChanges", "(", ")", ")", "{"...
Indication that tables in database require syncing before being matched with ORM models. @return bool
[ "Indication", "that", "tables", "in", "database", "require", "syncing", "before", "being", "matched", "with", "ORM", "models", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Schemas/SchemaBuilder.php#L297-L306
train
spiral/orm
source/Spiral/ORM/Schemas/SchemaBuilder.php
SchemaBuilder.renderModels
protected function renderModels() { foreach ($this->schemas as $schema) { /** * Attention, this method will request table schema from DBAL and will empty it's state * so schema can define it from ground zero! */ $table = $this->requestTable( $schema->getTable(), $schema->getDatabase(), true, true ); //Render table schema $table = $schema->declareTable($table); //Working with indexes foreach ($schema->getIndexes() as $index) { $table->index($index->getColumns())->unique($index->isUnique()); $table->index($index->getColumns())->setName($index->getName()); } /* * Attention, this is critical section: * * In order to work efficiently (like for real), ORM does require every table * to have 1 and only 1 primary key, this is crucial for things like in memory * cache, transaction command priority pipeline, multiple queue commands for one entity * and etc. * * It is planned to support user defined PKs in a future using unique indexes and record * schema. * * You are free to select any name for PK field. */ if (count($table->getPrimaryKeys()) !== 1) { throw new SchemaException( "Every record must have singular primary key (primary, bigPrimary types)" ); } //And put it back :) $this->pushTable($table); } }
php
protected function renderModels() { foreach ($this->schemas as $schema) { /** * Attention, this method will request table schema from DBAL and will empty it's state * so schema can define it from ground zero! */ $table = $this->requestTable( $schema->getTable(), $schema->getDatabase(), true, true ); //Render table schema $table = $schema->declareTable($table); //Working with indexes foreach ($schema->getIndexes() as $index) { $table->index($index->getColumns())->unique($index->isUnique()); $table->index($index->getColumns())->setName($index->getName()); } /* * Attention, this is critical section: * * In order to work efficiently (like for real), ORM does require every table * to have 1 and only 1 primary key, this is crucial for things like in memory * cache, transaction command priority pipeline, multiple queue commands for one entity * and etc. * * It is planned to support user defined PKs in a future using unique indexes and record * schema. * * You are free to select any name for PK field. */ if (count($table->getPrimaryKeys()) !== 1) { throw new SchemaException( "Every record must have singular primary key (primary, bigPrimary types)" ); } //And put it back :) $this->pushTable($table); } }
[ "protected", "function", "renderModels", "(", ")", "{", "foreach", "(", "$", "this", "->", "schemas", "as", "$", "schema", ")", "{", "/**\n * Attention, this method will request table schema from DBAL and will empty it's state\n * so schema can define it fro...
Walk thought schemas and define structure of associated tables. @throws SchemaException @throws DBALException
[ "Walk", "thought", "schemas", "and", "define", "structure", "of", "associated", "tables", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Schemas/SchemaBuilder.php#L379-L424
train
spiral/orm
source/Spiral/ORM/Schemas/SchemaBuilder.php
SchemaBuilder.renderRelations
protected function renderRelations() { foreach ($this->schemas as $schema) { foreach ($schema->getRelations() as $name => $relation) { //Source context defines where relation comes from $sourceContext = RelationContext::createContent( $schema, $this->requestTable($schema->getTable(), $schema->getDatabase()) ); //Target context might only exist if relation points to another record in ORM, //in some cases it might point outside of ORM scope $targetContext = null; if ($this->hasSchema($relation->getTarget())) { $target = $this->getSchema($relation->getTarget()); $targetContext = RelationContext::createContent( $target, $this->requestTable($target->getTable(), $target->getDatabase()) ); } $this->relations->registerRelation( $this, $relation->withContext($sourceContext, $targetContext) ); } } }
php
protected function renderRelations() { foreach ($this->schemas as $schema) { foreach ($schema->getRelations() as $name => $relation) { //Source context defines where relation comes from $sourceContext = RelationContext::createContent( $schema, $this->requestTable($schema->getTable(), $schema->getDatabase()) ); //Target context might only exist if relation points to another record in ORM, //in some cases it might point outside of ORM scope $targetContext = null; if ($this->hasSchema($relation->getTarget())) { $target = $this->getSchema($relation->getTarget()); $targetContext = RelationContext::createContent( $target, $this->requestTable($target->getTable(), $target->getDatabase()) ); } $this->relations->registerRelation( $this, $relation->withContext($sourceContext, $targetContext) ); } } }
[ "protected", "function", "renderRelations", "(", ")", "{", "foreach", "(", "$", "this", "->", "schemas", "as", "$", "schema", ")", "{", "foreach", "(", "$", "schema", "->", "getRelations", "(", ")", "as", "$", "name", "=>", "$", "relation", ")", "{", ...
Walk thought all record schemas, fetch and declare needed relations using relation manager. @throws SchemaException @throws DefinitionException
[ "Walk", "thought", "all", "record", "schemas", "fetch", "and", "declare", "needed", "relations", "using", "relation", "manager", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Schemas/SchemaBuilder.php#L432-L462
train
spiral/orm
source/Spiral/ORM/Schemas/SchemaBuilder.php
SchemaBuilder.pushTable
protected function pushTable(AbstractTable $schema) { //We have to make sure that local table name is used $table = substr($schema->getName(), strlen($schema->getPrefix())); if (empty($this->tables[$schema->getDriver()->getName() . '.' . $table])) { throw new SchemaException("AbstractTable must be requested before pushing back"); } $this->tables[$schema->getDriver()->getName() . '.' . $table] = $schema; }
php
protected function pushTable(AbstractTable $schema) { //We have to make sure that local table name is used $table = substr($schema->getName(), strlen($schema->getPrefix())); if (empty($this->tables[$schema->getDriver()->getName() . '.' . $table])) { throw new SchemaException("AbstractTable must be requested before pushing back"); } $this->tables[$schema->getDriver()->getName() . '.' . $table] = $schema; }
[ "protected", "function", "pushTable", "(", "AbstractTable", "$", "schema", ")", "{", "//We have to make sure that local table name is used", "$", "table", "=", "substr", "(", "$", "schema", "->", "getName", "(", ")", ",", "strlen", "(", "$", "schema", "->", "get...
Update table state. @param AbstractTable $schema @throws SchemaException
[ "Update", "table", "state", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Schemas/SchemaBuilder.php#L471-L481
train
spiral/orm
source/Spiral/ORM/Schemas/Relations/Traits/TablesTrait.php
TablesTrait.sourceTable
protected function sourceTable(SchemaBuilder $builder): AbstractTable { $source = $this->getDefinition()->sourceContext(); return $builder->requestTable($source->getTable(), $source->getDatabase()); }
php
protected function sourceTable(SchemaBuilder $builder): AbstractTable { $source = $this->getDefinition()->sourceContext(); return $builder->requestTable($source->getTable(), $source->getDatabase()); }
[ "protected", "function", "sourceTable", "(", "SchemaBuilder", "$", "builder", ")", ":", "AbstractTable", "{", "$", "source", "=", "$", "this", "->", "getDefinition", "(", ")", "->", "sourceContext", "(", ")", ";", "return", "$", "builder", "->", "requestTabl...
Get table linked with source relation model. @param SchemaBuilder $builder @return AbstractTable @throws RelationSchemaException
[ "Get", "table", "linked", "with", "source", "relation", "model", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Schemas/Relations/Traits/TablesTrait.php#L26-L31
train
spiral/orm
source/Spiral/ORM/Schemas/Relations/Traits/TablesTrait.php
TablesTrait.targetTable
protected function targetTable(SchemaBuilder $builder): AbstractTable { $target = $this->getDefinition()->targetContext(); if (empty($target)) { throw new RelationSchemaException(sprintf( "Unable to get target context '%s' in '%s'.'%s'", $this->getDefinition()->getTarget(), $this->getDefinition()->sourceContext()->getClass(), $this->getDefinition()->getName() )); } return $builder->requestTable($target->getTable(), $target->getDatabase()); }
php
protected function targetTable(SchemaBuilder $builder): AbstractTable { $target = $this->getDefinition()->targetContext(); if (empty($target)) { throw new RelationSchemaException(sprintf( "Unable to get target context '%s' in '%s'.'%s'", $this->getDefinition()->getTarget(), $this->getDefinition()->sourceContext()->getClass(), $this->getDefinition()->getName() )); } return $builder->requestTable($target->getTable(), $target->getDatabase()); }
[ "protected", "function", "targetTable", "(", "SchemaBuilder", "$", "builder", ")", ":", "AbstractTable", "{", "$", "target", "=", "$", "this", "->", "getDefinition", "(", ")", "->", "targetContext", "(", ")", ";", "if", "(", "empty", "(", "$", "target", ...
Get table linked with target relation model. @param SchemaBuilder $builder @return AbstractTable @throws RelationSchemaException
[ "Get", "table", "linked", "with", "target", "relation", "model", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Schemas/Relations/Traits/TablesTrait.php#L42-L55
train
spiral/orm
source/Spiral/ORM/Record.php
Record.save
public function save(TransactionInterface $transaction = null, bool $queueRelations = true): int { /* * First, per interface agreement calculate entity state after save command being called. */ if (!$this->isLoaded()) { $state = self::CREATED; } elseif (!$this->hasChanges()) { $state = self::UPDATED; } else { $state = self::UNCHANGED; } if (empty($transaction)) { /* * When no transaction is given we will create our own and run it immediately. */ $transaction = $transaction ?? new Transaction(); $transaction->store($this, $queueRelations); $transaction->run(); } else { $transaction->addCommand($this->queueStore($queueRelations)); } return $state; }
php
public function save(TransactionInterface $transaction = null, bool $queueRelations = true): int { /* * First, per interface agreement calculate entity state after save command being called. */ if (!$this->isLoaded()) { $state = self::CREATED; } elseif (!$this->hasChanges()) { $state = self::UPDATED; } else { $state = self::UNCHANGED; } if (empty($transaction)) { /* * When no transaction is given we will create our own and run it immediately. */ $transaction = $transaction ?? new Transaction(); $transaction->store($this, $queueRelations); $transaction->run(); } else { $transaction->addCommand($this->queueStore($queueRelations)); } return $state; }
[ "public", "function", "save", "(", "TransactionInterface", "$", "transaction", "=", "null", ",", "bool", "$", "queueRelations", "=", "true", ")", ":", "int", "{", "/*\n * First, per interface agreement calculate entity state after save command being called.\n */...
Sync entity with database, when no transaction is given ActiveRecord will create and run it automatically. @param TransactionInterface|null $transaction @param bool $queueRelations @return int
[ "Sync", "entity", "with", "database", "when", "no", "transaction", "is", "given", "ActiveRecord", "will", "create", "and", "run", "it", "automatically", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Record.php#L26-L51
train
spiral/orm
source/Spiral/ORM/Record.php
Record.delete
public function delete(TransactionInterface $transaction = null) { if (empty($transaction)) { /* * When no transaction is given we will create our own and run it immediately. */ $transaction = $transaction ?? new Transaction(); $transaction->delete($this); $transaction->run(); } else { $transaction->addCommand($this->queueDelete()); } }
php
public function delete(TransactionInterface $transaction = null) { if (empty($transaction)) { /* * When no transaction is given we will create our own and run it immediately. */ $transaction = $transaction ?? new Transaction(); $transaction->delete($this); $transaction->run(); } else { $transaction->addCommand($this->queueDelete()); } }
[ "public", "function", "delete", "(", "TransactionInterface", "$", "transaction", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "transaction", ")", ")", "{", "/*\n * When no transaction is given we will create our own and run it immediately.\n */...
Delete entity in database, when no transaction is given ActiveRecord will create and run it automatically. @param TransactionInterface|null $transaction
[ "Delete", "entity", "in", "database", "when", "no", "transaction", "is", "given", "ActiveRecord", "will", "create", "and", "run", "it", "automatically", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Record.php#L59-L71
train
rinvex/cortex-foundation
src/DataTables/AbstractDataTable.php
AbstractDataTable.filename
protected function filename(): string { $model = $this->model ?? trim(str_replace('DataTable', '', mb_strrchr(static::class, '\\')), " \t\n\r\0\x0B\\"); $resource = str_plural(mb_strtolower(array_last(explode(class_exists($model) ? '\\' : '.', $model)))); return $resource.'-export-'.date('Y-m-d').'-'.time(); }
php
protected function filename(): string { $model = $this->model ?? trim(str_replace('DataTable', '', mb_strrchr(static::class, '\\')), " \t\n\r\0\x0B\\"); $resource = str_plural(mb_strtolower(array_last(explode(class_exists($model) ? '\\' : '.', $model)))); return $resource.'-export-'.date('Y-m-d').'-'.time(); }
[ "protected", "function", "filename", "(", ")", ":", "string", "{", "$", "model", "=", "$", "this", "->", "model", "??", "trim", "(", "str_replace", "(", "'DataTable'", ",", "''", ",", "mb_strrchr", "(", "static", "::", "class", ",", "'\\\\'", ")", ")",...
Get filename for export. @return string
[ "Get", "filename", "for", "export", "." ]
230c100d98131c76f777e5036b3e7cd83af49e6e
https://github.com/rinvex/cortex-foundation/blob/230c100d98131c76f777e5036b3e7cd83af49e6e/src/DataTables/AbstractDataTable.php#L197-L204
train
swoft-cloud/swoft-rpc-server
src/Command/RpcCommand.php
RpcCommand.start
public function start() { $rpcServer = $this->getRpcServer(); // 是否正在运行 if ($rpcServer->isRunning()) { $serverStatus = $rpcServer->getServerSetting(); \output()->writeln("<error>The server have been running!(PID: {$serverStatus['masterPid']})</error>", true, true); } // 选项参数解析 $this->setStartArgs($rpcServer); $tcpStatus = $rpcServer->getTcpSetting(); // tcp启动参数 $tcpHost = $tcpStatus['host']; $tcpPort = $tcpStatus['port']; $tcpType = $tcpStatus['type']; $tcpMode = $tcpStatus['mode']; // 信息面板 $lines = [ ' Information Panel ', '*************************************************************', "* tcp | Host: <note>$tcpHost</note>, port: <note>$tcpPort</note>, mode: <note>$tcpMode</note>, type: <note>$tcpType</note>", '*************************************************************', ]; \output()->writeln(implode("\n", $lines)); // 启动 $rpcServer->start(); }
php
public function start() { $rpcServer = $this->getRpcServer(); // 是否正在运行 if ($rpcServer->isRunning()) { $serverStatus = $rpcServer->getServerSetting(); \output()->writeln("<error>The server have been running!(PID: {$serverStatus['masterPid']})</error>", true, true); } // 选项参数解析 $this->setStartArgs($rpcServer); $tcpStatus = $rpcServer->getTcpSetting(); // tcp启动参数 $tcpHost = $tcpStatus['host']; $tcpPort = $tcpStatus['port']; $tcpType = $tcpStatus['type']; $tcpMode = $tcpStatus['mode']; // 信息面板 $lines = [ ' Information Panel ', '*************************************************************', "* tcp | Host: <note>$tcpHost</note>, port: <note>$tcpPort</note>, mode: <note>$tcpMode</note>, type: <note>$tcpType</note>", '*************************************************************', ]; \output()->writeln(implode("\n", $lines)); // 启动 $rpcServer->start(); }
[ "public", "function", "start", "(", ")", "{", "$", "rpcServer", "=", "$", "this", "->", "getRpcServer", "(", ")", ";", "// 是否正在运行", "if", "(", "$", "rpcServer", "->", "isRunning", "(", ")", ")", "{", "$", "serverStatus", "=", "$", "rpcServer", "->", ...
start rpc server @Usage {fullCommand} [-d|--daemon] @Options -d, --daemon Run server on the background @Example {fullCommand} {fullCommand} -d
[ "start", "rpc", "server" ]
527ce20421ad46919b16ebdcc12658f0e3807a07
https://github.com/swoft-cloud/swoft-rpc-server/blob/527ce20421ad46919b16ebdcc12658f0e3807a07/src/Command/RpcCommand.php#L24-L55
train
swoft-cloud/swoft-rpc-server
src/Command/RpcCommand.php
RpcCommand.reload
public function reload() { $rpcServer = $this->getRpcServer(); // 是否已启动 if (! $rpcServer->isRunning()) { output()->writeln('<error>The server is not running! cannot reload</error>', true, true); } // 打印信息 output()->writeln(sprintf('<info>Server %s is reloading ...</info>', input()->getFullScript())); // 重载 $reloadTask = input()->hasOpt('t'); $rpcServer->reload($reloadTask); output()->writeln(sprintf('<success>Server %s is reload success</success>', input()->getFullScript())); }
php
public function reload() { $rpcServer = $this->getRpcServer(); // 是否已启动 if (! $rpcServer->isRunning()) { output()->writeln('<error>The server is not running! cannot reload</error>', true, true); } // 打印信息 output()->writeln(sprintf('<info>Server %s is reloading ...</info>', input()->getFullScript())); // 重载 $reloadTask = input()->hasOpt('t'); $rpcServer->reload($reloadTask); output()->writeln(sprintf('<success>Server %s is reload success</success>', input()->getFullScript())); }
[ "public", "function", "reload", "(", ")", "{", "$", "rpcServer", "=", "$", "this", "->", "getRpcServer", "(", ")", ";", "// 是否已启动", "if", "(", "!", "$", "rpcServer", "->", "isRunning", "(", ")", ")", "{", "output", "(", ")", "->", "writeln", "(", "...
reload worker process @Usage {fullCommand} [arguments] [options] @Options -t Only to reload task processes, default to reload worker and task @Example php swoft.php rpc:reload
[ "reload", "worker", "process" ]
527ce20421ad46919b16ebdcc12658f0e3807a07
https://github.com/swoft-cloud/swoft-rpc-server/blob/527ce20421ad46919b16ebdcc12658f0e3807a07/src/Command/RpcCommand.php#L67-L83
train
swoft-cloud/swoft-rpc-server
src/Command/RpcCommand.php
RpcCommand.stop
public function stop() { $rpcServer = $this->getRpcServer(); // 是否已启动 if (! $rpcServer->isRunning()) { \output()->writeln('<error>The server is not running! cannot stop</error>', true, true); } // pid文件 $serverStatus = $rpcServer->getServerSetting(); $pidFile = $serverStatus['pfile']; \output()->writeln(sprintf('<info>Swoft %s is stopping ...</info>', input()->getFullScript())); $result = $rpcServer->stop(); // 停止失败 if (! $result) { \output()->writeln(sprintf('<error>Swoft %s stop fail</error>', input()->getFullScript())); } //删除pid文件 @unlink($pidFile); \output()->writeln(sprintf('<success>Swoft %s stop success</success>', input()->getFullScript())); }
php
public function stop() { $rpcServer = $this->getRpcServer(); // 是否已启动 if (! $rpcServer->isRunning()) { \output()->writeln('<error>The server is not running! cannot stop</error>', true, true); } // pid文件 $serverStatus = $rpcServer->getServerSetting(); $pidFile = $serverStatus['pfile']; \output()->writeln(sprintf('<info>Swoft %s is stopping ...</info>', input()->getFullScript())); $result = $rpcServer->stop(); // 停止失败 if (! $result) { \output()->writeln(sprintf('<error>Swoft %s stop fail</error>', input()->getFullScript())); } //删除pid文件 @unlink($pidFile); \output()->writeln(sprintf('<success>Swoft %s stop success</success>', input()->getFullScript())); }
[ "public", "function", "stop", "(", ")", "{", "$", "rpcServer", "=", "$", "this", "->", "getRpcServer", "(", ")", ";", "// 是否已启动", "if", "(", "!", "$", "rpcServer", "->", "isRunning", "(", ")", ")", "{", "\\", "output", "(", ")", "->", "writeln", "(...
stop rpc server @Usage {fullCommand} @Example {fullCommand}
[ "stop", "rpc", "server" ]
527ce20421ad46919b16ebdcc12658f0e3807a07
https://github.com/swoft-cloud/swoft-rpc-server/blob/527ce20421ad46919b16ebdcc12658f0e3807a07/src/Command/RpcCommand.php#L91-L116
train
swoft-cloud/swoft-rpc-server
src/Command/RpcCommand.php
RpcCommand.restart
public function restart() { $rpcServer = $this->getRpcServer(); // 是否已启动 if ($rpcServer->isRunning()) { $this->stop(); } // 重启默认是守护进程 $rpcServer->setDaemonize(); $this->start(); }
php
public function restart() { $rpcServer = $this->getRpcServer(); // 是否已启动 if ($rpcServer->isRunning()) { $this->stop(); } // 重启默认是守护进程 $rpcServer->setDaemonize(); $this->start(); }
[ "public", "function", "restart", "(", ")", "{", "$", "rpcServer", "=", "$", "this", "->", "getRpcServer", "(", ")", ";", "// 是否已启动", "if", "(", "$", "rpcServer", "->", "isRunning", "(", ")", ")", "{", "$", "this", "->", "stop", "(", ")", ";", "}", ...
restart rpc server @Usage {fullCommand} @Options -d, --daemon Run server on the background @Example {fullCommand} {fullCommand} -d
[ "restart", "rpc", "server" ]
527ce20421ad46919b16ebdcc12658f0e3807a07
https://github.com/swoft-cloud/swoft-rpc-server/blob/527ce20421ad46919b16ebdcc12658f0e3807a07/src/Command/RpcCommand.php#L128-L140
train
spiral/orm
source/Spiral/ORM/Traits/SourceTrait.php
SourceTrait.source
public static function source(): RecordSource { /** * Container to be received via global scope. * * @var ContainerInterface $container */ //Via global scope $container = self::staticContainer(); if (empty($container)) { //Via global scope throw new ScopeException(sprintf( "Unable to get '%s' source, no container scope is available", static::class )); } return $container->get(ORMInterface::class)->source(static::class); }
php
public static function source(): RecordSource { /** * Container to be received via global scope. * * @var ContainerInterface $container */ //Via global scope $container = self::staticContainer(); if (empty($container)) { //Via global scope throw new ScopeException(sprintf( "Unable to get '%s' source, no container scope is available", static::class )); } return $container->get(ORMInterface::class)->source(static::class); }
[ "public", "static", "function", "source", "(", ")", ":", "RecordSource", "{", "/**\n * Container to be received via global scope.\n *\n * @var ContainerInterface $container\n */", "//Via global scope", "$", "container", "=", "self", "::", "staticContai...
Instance of RecordSource associated with specific model. @see Component::staticContainer() * @return RecordSource @throws ScopeException
[ "Instance", "of", "RecordSource", "associated", "with", "specific", "model", "." ]
a301cd1b664e65496dab648d77ee92bf4fb6949b
https://github.com/spiral/orm/blob/a301cd1b664e65496dab648d77ee92bf4fb6949b/source/Spiral/ORM/Traits/SourceTrait.php#L87-L106
train
swoft-cloud/swoft-rpc-server
src/Validator/ServiceValidator.php
ServiceValidator.getServiceArgs
private function getServiceArgs(array $serviceHandler, array $serviceData): array { list($className, $method) = $serviceHandler; $rc = new \ReflectionClass($className); $rm = $rc->getMethod($method); $mps = $rm->getParameters(); $params = $serviceData['params'] ?? []; if (empty($params)) { return []; } $index = 0; $args = []; foreach ($mps as $mp) { $name = $mp->getName(); if (! isset($params[$index])) { break; } $args[$name] = $params[$index]; $index++; } return $args; }
php
private function getServiceArgs(array $serviceHandler, array $serviceData): array { list($className, $method) = $serviceHandler; $rc = new \ReflectionClass($className); $rm = $rc->getMethod($method); $mps = $rm->getParameters(); $params = $serviceData['params'] ?? []; if (empty($params)) { return []; } $index = 0; $args = []; foreach ($mps as $mp) { $name = $mp->getName(); if (! isset($params[$index])) { break; } $args[$name] = $params[$index]; $index++; } return $args; }
[ "private", "function", "getServiceArgs", "(", "array", "$", "serviceHandler", ",", "array", "$", "serviceData", ")", ":", "array", "{", "list", "(", "$", "className", ",", "$", "method", ")", "=", "$", "serviceHandler", ";", "$", "rc", "=", "new", "\\", ...
get args of called function @param array $serviceHandler @param array $serviceData @return array @throws \ReflectionException
[ "get", "args", "of", "called", "function" ]
527ce20421ad46919b16ebdcc12658f0e3807a07
https://github.com/swoft-cloud/swoft-rpc-server/blob/527ce20421ad46919b16ebdcc12658f0e3807a07/src/Validator/ServiceValidator.php#L56-L80
train
mirko-pagliai/cakephp-assets
src/Utility/AssetsCreator.php
AssetsCreator.resolveAssetPath
protected function resolveAssetPath() { $basename = md5(serialize(array_map(function ($path) { return [$path, filemtime($path)]; }, $this->paths))); return Configure::read('Assets.target') . DS . $basename . '.' . $this->type; }
php
protected function resolveAssetPath() { $basename = md5(serialize(array_map(function ($path) { return [$path, filemtime($path)]; }, $this->paths))); return Configure::read('Assets.target') . DS . $basename . '.' . $this->type; }
[ "protected", "function", "resolveAssetPath", "(", ")", "{", "$", "basename", "=", "md5", "(", "serialize", "(", "array_map", "(", "function", "(", "$", "path", ")", "{", "return", "[", "$", "path", ",", "filemtime", "(", "$", "path", ")", "]", ";", "...
Internal method to resolve the asset path @return string Asset full path @use $paths @use $type
[ "Internal", "method", "to", "resolve", "the", "asset", "path" ]
5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b
https://github.com/mirko-pagliai/cakephp-assets/blob/5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b/src/Utility/AssetsCreator.php#L73-L80
train
mirko-pagliai/cakephp-assets
src/Utility/AssetsCreator.php
AssetsCreator.resolveFilePaths
protected function resolveFilePaths($paths) { $loadedPlugins = Plugin::loaded(); return array_map(function ($path) use ($loadedPlugins) { $pluginSplit = pluginSplit($path); //Note that using `pluginSplit()` is not sufficient, because // `$path` may still contain a dot if (!empty($pluginSplit[0]) && in_array($pluginSplit[0], $loadedPlugins)) { list($plugin, $path) = $pluginSplit; } $path = string_starts_with($path, '/') ? substr($path, 1) : $this->type . DS . $path; $path = DS === '/' ? $path : $path = str_replace('/', DS, $path); $path = empty($plugin) ? WWW_ROOT . $path : Plugin::path($plugin) . 'webroot' . DS . $path; //Appends the file extension, if not already present $path = pathinfo($path, PATHINFO_EXTENSION) == $this->type ? $path : sprintf('%s.%s', $path, $this->type); is_readable_or_fail($path); return $path; }, (array)$paths); }
php
protected function resolveFilePaths($paths) { $loadedPlugins = Plugin::loaded(); return array_map(function ($path) use ($loadedPlugins) { $pluginSplit = pluginSplit($path); //Note that using `pluginSplit()` is not sufficient, because // `$path` may still contain a dot if (!empty($pluginSplit[0]) && in_array($pluginSplit[0], $loadedPlugins)) { list($plugin, $path) = $pluginSplit; } $path = string_starts_with($path, '/') ? substr($path, 1) : $this->type . DS . $path; $path = DS === '/' ? $path : $path = str_replace('/', DS, $path); $path = empty($plugin) ? WWW_ROOT . $path : Plugin::path($plugin) . 'webroot' . DS . $path; //Appends the file extension, if not already present $path = pathinfo($path, PATHINFO_EXTENSION) == $this->type ? $path : sprintf('%s.%s', $path, $this->type); is_readable_or_fail($path); return $path; }, (array)$paths); }
[ "protected", "function", "resolveFilePaths", "(", "$", "paths", ")", "{", "$", "loadedPlugins", "=", "Plugin", "::", "loaded", "(", ")", ";", "return", "array_map", "(", "function", "(", "$", "path", ")", "use", "(", "$", "loadedPlugins", ")", "{", "$", ...
Internal method to resolve partial file paths and return full paths @param string|array $paths Partial file paths @return array Full file paths @use $type
[ "Internal", "method", "to", "resolve", "partial", "file", "paths", "and", "return", "full", "paths" ]
5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b
https://github.com/mirko-pagliai/cakephp-assets/blob/5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b/src/Utility/AssetsCreator.php#L88-L111
train
mirko-pagliai/cakephp-assets
src/Utility/AssetsCreator.php
AssetsCreator.create
public function create() { $File = new File($this->path()); if (!$File->readable()) { $minifier = $this->type === 'css' ? new Minify\CSS() : new Minify\JS(); array_map([$minifier, 'add'], $this->paths); //Writes the file $success = $File->write($minifier->minify()); is_true_or_fail($success, __d('assets', 'Failed to create file {0}', rtr($this->path()))); } return $this->filename(); }
php
public function create() { $File = new File($this->path()); if (!$File->readable()) { $minifier = $this->type === 'css' ? new Minify\CSS() : new Minify\JS(); array_map([$minifier, 'add'], $this->paths); //Writes the file $success = $File->write($minifier->minify()); is_true_or_fail($success, __d('assets', 'Failed to create file {0}', rtr($this->path()))); } return $this->filename(); }
[ "public", "function", "create", "(", ")", "{", "$", "File", "=", "new", "File", "(", "$", "this", "->", "path", "(", ")", ")", ";", "if", "(", "!", "$", "File", "->", "readable", "(", ")", ")", "{", "$", "minifier", "=", "$", "this", "->", "t...
Creates the asset @return string @throws RuntimeException @uses filename() @uses path() @uses $paths @uses $type
[ "Creates", "the", "asset" ]
5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b
https://github.com/mirko-pagliai/cakephp-assets/blob/5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b/src/Utility/AssetsCreator.php#L122-L136
train
spiral/security
src/Matcher.php
Matcher.matches
public function matches(string $string, string $pattern): bool { if ($string === $pattern) { return true; } if (!$this->isPattern($pattern)) { return false; } return (bool)preg_match($this->getRegex($pattern), $string); }
php
public function matches(string $string, string $pattern): bool { if ($string === $pattern) { return true; } if (!$this->isPattern($pattern)) { return false; } return (bool)preg_match($this->getRegex($pattern), $string); }
[ "public", "function", "matches", "(", "string", "$", "string", ",", "string", "$", "pattern", ")", ":", "bool", "{", "if", "(", "$", "string", "===", "$", "pattern", ")", "{", "return", "true", ";", "}", "if", "(", "!", "$", "this", "->", "isPatter...
Checks if string matches given pattent. @param string $string @param string $pattern @return bool
[ "Checks", "if", "string", "matches", "given", "pattent", "." ]
a36decbf237460e1e2059bb12b41c69a1cd59ec3
https://github.com/spiral/security/blob/a36decbf237460e1e2059bb12b41c69a1cd59ec3/src/Matcher.php#L39-L48
train
spiral/security
src/Traits/GuardedTrait.php
GuardedTrait.resolvePermission
protected function resolvePermission(string $permission): string { if (defined('static::GUARD_NAMESPACE')) { //Yay! Isolation $permission = constant(get_called_class() . '::' . 'GUARD_NAMESPACE') . '.' . $permission; } return $permission; }
php
protected function resolvePermission(string $permission): string { if (defined('static::GUARD_NAMESPACE')) { //Yay! Isolation $permission = constant(get_called_class() . '::' . 'GUARD_NAMESPACE') . '.' . $permission; } return $permission; }
[ "protected", "function", "resolvePermission", "(", "string", "$", "permission", ")", ":", "string", "{", "if", "(", "defined", "(", "'static::GUARD_NAMESPACE'", ")", ")", "{", "//Yay! Isolation", "$", "permission", "=", "constant", "(", "get_called_class", "(", ...
Automatically prepend permission name with local RBAC namespace. @param string $permission @return string
[ "Automatically", "prepend", "permission", "name", "with", "local", "RBAC", "namespace", "." ]
a36decbf237460e1e2059bb12b41c69a1cd59ec3
https://github.com/spiral/security/blob/a36decbf237460e1e2059bb12b41c69a1cd59ec3/src/Traits/GuardedTrait.php#L64-L72
train
spiral/security
src/RuleManager.php
RuleManager.validateRule
private function validateRule($rule): bool { if ($rule instanceof \Closure || $rule instanceof RuleInterface) { return true; } if (is_array($rule)) { return is_callable($rule, true); } if (is_string($rule) && class_exists($rule)) { try { $reflection = new \ReflectionClass($rule); } catch (\ReflectionException $e) { return false; } return $reflection->isSubclassOf(RuleInterface::class); } return false; }
php
private function validateRule($rule): bool { if ($rule instanceof \Closure || $rule instanceof RuleInterface) { return true; } if (is_array($rule)) { return is_callable($rule, true); } if (is_string($rule) && class_exists($rule)) { try { $reflection = new \ReflectionClass($rule); } catch (\ReflectionException $e) { return false; } return $reflection->isSubclassOf(RuleInterface::class); } return false; }
[ "private", "function", "validateRule", "(", "$", "rule", ")", ":", "bool", "{", "if", "(", "$", "rule", "instanceof", "\\", "Closure", "||", "$", "rule", "instanceof", "RuleInterface", ")", "{", "return", "true", ";", "}", "if", "(", "is_array", "(", "...
Must return true if rule is valid. @param mixed $rule @return bool
[ "Must", "return", "true", "if", "rule", "is", "valid", "." ]
a36decbf237460e1e2059bb12b41c69a1cd59ec3
https://github.com/spiral/security/blob/a36decbf237460e1e2059bb12b41c69a1cd59ec3/src/RuleManager.php#L135-L156
train
mirko-pagliai/cakephp-assets
src/View/Helper/AssetHelper.php
AssetHelper.path
protected function path($path, $type) { if (Configure::read('debug') && !Configure::read('Assets.force')) { return $path; } $asset = new AssetsCreator($path, $type); $path = '/assets/' . $asset->create(); //Appends the timestamp $stamp = Configure::read('Asset.timestamp'); if ($stamp === 'force' || ($stamp === true && Configure::read('debug'))) { $path = sprintf('%s.%s?%s', $path, $type, filemtime($asset->path())); } return $path; }
php
protected function path($path, $type) { if (Configure::read('debug') && !Configure::read('Assets.force')) { return $path; } $asset = new AssetsCreator($path, $type); $path = '/assets/' . $asset->create(); //Appends the timestamp $stamp = Configure::read('Asset.timestamp'); if ($stamp === 'force' || ($stamp === true && Configure::read('debug'))) { $path = sprintf('%s.%s?%s', $path, $type, filemtime($asset->path())); } return $path; }
[ "protected", "function", "path", "(", "$", "path", ",", "$", "type", ")", "{", "if", "(", "Configure", "::", "read", "(", "'debug'", ")", "&&", "!", "Configure", "::", "read", "(", "'Assets.force'", ")", ")", "{", "return", "$", "path", ";", "}", "...
Gets the asset path @param string|array $path String or array of css/js files @param string $type `css` or `js` @return string Asset path @uses Assets\Utility\AssetsCreator::create() @uses Assets\Utility\AssetsCreator::path()
[ "Gets", "the", "asset", "path" ]
5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b
https://github.com/mirko-pagliai/cakephp-assets/blob/5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b/src/View/Helper/AssetHelper.php#L40-L56
train
mirko-pagliai/cakephp-assets
src/View/Helper/AssetHelper.php
AssetHelper.css
public function css($path, array $options = []) { return $this->Html->css($this->path($path, 'css'), $options); }
php
public function css($path, array $options = []) { return $this->Html->css($this->path($path, 'css'), $options); }
[ "public", "function", "css", "(", "$", "path", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "$", "this", "->", "Html", "->", "css", "(", "$", "this", "->", "path", "(", "$", "path", ",", "'css'", ")", ",", "$", "options", ")...
Compresses and adds a css file to the layout @param string|array $path String or array of css files @param array $options Array of options and HTML attributes @return string Html, `<link>` or `<style>` tag @uses path()
[ "Compresses", "and", "adds", "a", "css", "file", "to", "the", "layout" ]
5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b
https://github.com/mirko-pagliai/cakephp-assets/blob/5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b/src/View/Helper/AssetHelper.php#L65-L68
train
mirko-pagliai/cakephp-assets
src/View/Helper/AssetHelper.php
AssetHelper.script
public function script($url, array $options = []) { return $this->Html->script($this->path($url, 'js'), $options); }
php
public function script($url, array $options = []) { return $this->Html->script($this->path($url, 'js'), $options); }
[ "public", "function", "script", "(", "$", "url", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "$", "this", "->", "Html", "->", "script", "(", "$", "this", "->", "path", "(", "$", "url", ",", "'js'", ")", ",", "$", "options", ...
Compresses and adds js files to the layout @param string|array $url String or array of js files @param array $options Array of options and HTML attributes @return mixed String of `<script />` tags or null if `$inline` is false or if `$once` is true @uses path()
[ "Compresses", "and", "adds", "js", "files", "to", "the", "layout" ]
5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b
https://github.com/mirko-pagliai/cakephp-assets/blob/5bbe4963e177bfbd4c152e92edaa5eeeb0c6d64b/src/View/Helper/AssetHelper.php#L78-L81
train
joomla-framework/archive
src/Gzip.php
Gzip.extract
public function extract($archive, $destination) { $this->data = null; if (!isset($this->options['use_streams']) || $this->options['use_streams'] == false) { $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } $position = $this->getFilePosition(); $buffer = gzinflate(substr($this->data, $position, \strlen($this->data) - $position)); if (empty($buffer)) { throw new \RuntimeException('Unable to decompress data'); } if (!File::write($destination, $buffer)) { throw new \RuntimeException('Unable to write archive to file ' . $destination); } } else { // New style! streams! $input = Stream::getStream(); // Use gz $input->set('processingmethod', 'gz'); if (!$input->open($archive)) { throw new \RuntimeException('Unable to read archive'); } $output = Stream::getStream(); if (!$output->open($destination, 'w')) { $input->close(); throw new \RuntimeException('Unable to open file "' . $destination . '" for writing'); } do { $this->data = $input->read($input->get('chunksize', 8196)); if ($this->data) { if (!$output->write($this->data)) { $input->close(); throw new \RuntimeException('Unable to write archive to file ' . $destination); } } } while ($this->data); $output->close(); $input->close(); } return true; }
php
public function extract($archive, $destination) { $this->data = null; if (!isset($this->options['use_streams']) || $this->options['use_streams'] == false) { $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } $position = $this->getFilePosition(); $buffer = gzinflate(substr($this->data, $position, \strlen($this->data) - $position)); if (empty($buffer)) { throw new \RuntimeException('Unable to decompress data'); } if (!File::write($destination, $buffer)) { throw new \RuntimeException('Unable to write archive to file ' . $destination); } } else { // New style! streams! $input = Stream::getStream(); // Use gz $input->set('processingmethod', 'gz'); if (!$input->open($archive)) { throw new \RuntimeException('Unable to read archive'); } $output = Stream::getStream(); if (!$output->open($destination, 'w')) { $input->close(); throw new \RuntimeException('Unable to open file "' . $destination . '" for writing'); } do { $this->data = $input->read($input->get('chunksize', 8196)); if ($this->data) { if (!$output->write($this->data)) { $input->close(); throw new \RuntimeException('Unable to write archive to file ' . $destination); } } } while ($this->data); $output->close(); $input->close(); } return true; }
[ "public", "function", "extract", "(", "$", "archive", ",", "$", "destination", ")", "{", "$", "this", "->", "data", "=", "null", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "options", "[", "'use_streams'", "]", ")", "||", "$", "this", "->...
Extract a Gzip compressed file to a given path @param string $archive Path to ZIP archive to extract @param string $destination Path to extract archive to @return boolean True if successful @since 1.0 @throws \RuntimeException
[ "Extract", "a", "Gzip", "compressed", "file", "to", "a", "given", "path" ]
b1d496e8c7814f1e376cb14296c38d5ef4e08c78
https://github.com/joomla-framework/archive/blob/b1d496e8c7814f1e376cb14296c38d5ef4e08c78/src/Gzip.php#L82-L151
train
joomla-framework/archive
src/Gzip.php
Gzip.getFilePosition
public function getFilePosition() { // Gzipped file... unpack it first $position = 0; $info = @ unpack('CCM/CFLG/VTime/CXFL/COS', substr($this->data, $position + 2)); if (!$info) { throw new \RuntimeException('Unable to decompress data.'); } $position += 10; if ($info['FLG'] & $this->flags['FEXTRA']) { $XLEN = unpack('vLength', substr($this->data, $position + 0, 2)); $XLEN = $XLEN['Length']; $position += $XLEN + 2; } if ($info['FLG'] & $this->flags['FNAME']) { $filenamePos = strpos($this->data, "\x0", $position); $position = $filenamePos + 1; } if ($info['FLG'] & $this->flags['FCOMMENT']) { $commentPos = strpos($this->data, "\x0", $position); $position = $commentPos + 1; } if ($info['FLG'] & $this->flags['FHCRC']) { $hcrc = unpack('vCRC', substr($this->data, $position + 0, 2)); $hcrc = $hcrc['CRC']; $position += 2; } return $position; }
php
public function getFilePosition() { // Gzipped file... unpack it first $position = 0; $info = @ unpack('CCM/CFLG/VTime/CXFL/COS', substr($this->data, $position + 2)); if (!$info) { throw new \RuntimeException('Unable to decompress data.'); } $position += 10; if ($info['FLG'] & $this->flags['FEXTRA']) { $XLEN = unpack('vLength', substr($this->data, $position + 0, 2)); $XLEN = $XLEN['Length']; $position += $XLEN + 2; } if ($info['FLG'] & $this->flags['FNAME']) { $filenamePos = strpos($this->data, "\x0", $position); $position = $filenamePos + 1; } if ($info['FLG'] & $this->flags['FCOMMENT']) { $commentPos = strpos($this->data, "\x0", $position); $position = $commentPos + 1; } if ($info['FLG'] & $this->flags['FHCRC']) { $hcrc = unpack('vCRC', substr($this->data, $position + 0, 2)); $hcrc = $hcrc['CRC']; $position += 2; } return $position; }
[ "public", "function", "getFilePosition", "(", ")", "{", "// Gzipped file... unpack it first", "$", "position", "=", "0", ";", "$", "info", "=", "@", "unpack", "(", "'CCM/CFLG/VTime/CXFL/COS'", ",", "substr", "(", "$", "this", "->", "data", ",", "$", "position"...
Get file data offset for archive @return integer Data position marker for archive @since 1.0 @throws \RuntimeException
[ "Get", "file", "data", "offset", "for", "archive" ]
b1d496e8c7814f1e376cb14296c38d5ef4e08c78
https://github.com/joomla-framework/archive/blob/b1d496e8c7814f1e376cb14296c38d5ef4e08c78/src/Gzip.php#L173-L213
train
Domraider/rxnet
src/Rxnet/Httpd/RequestParser.php
RequestParser.parseChunk
public function parseChunk($data) { if (!$data) { return; } // Detect end of transfer if ($end = strpos($data, "0\r\n\r\n")) { $data = substr($data, 0, $end); } $this->buffer.= $data; $this->request->onData($data); if ($end) { $this->buffer = $this->parseChunkedBuffer($this->buffer); $this->request->setBody($this->buffer); $this->notifyCompleted(); $this->buffer = ''; } }
php
public function parseChunk($data) { if (!$data) { return; } // Detect end of transfer if ($end = strpos($data, "0\r\n\r\n")) { $data = substr($data, 0, $end); } $this->buffer.= $data; $this->request->onData($data); if ($end) { $this->buffer = $this->parseChunkedBuffer($this->buffer); $this->request->setBody($this->buffer); $this->notifyCompleted(); $this->buffer = ''; } }
[ "public", "function", "parseChunk", "(", "$", "data", ")", "{", "if", "(", "!", "$", "data", ")", "{", "return", ";", "}", "// Detect end of transfer", "if", "(", "$", "end", "=", "strpos", "(", "$", "data", ",", "\"0\\r\\n\\r\\n\"", ")", ")", "{", "...
Wait end of transfer packet to complete @param $data
[ "Wait", "end", "of", "transfer", "packet", "to", "complete" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Httpd/RequestParser.php#L128-L146
train
UseMuffin/Tags
src/Model/Entity/TagAwareTrait.php
TagAwareTrait.untag
public function untag($tags = null) { if (empty($tags)) { return $this->_updateTags([], 'replace'); } $table = TableRegistry::getTableLocator()->get($this->source()); $behavior = $table->behaviors()->Tag; $assoc = $table->getAssociation($behavior->getConfig('tagsAlias')); $property = $assoc->getProperty(); $id = $this->get($table->getPrimaryKey()); $untags = $behavior->normalizeTags($tags); $tags = $this->get($property); if (!$tags) { $contain = [$behavior->getConfig('tagsAlias')]; $tags = $table->get($id, compact('contain'))->get($property); } $tagsTable = $table->{$behavior->getConfig('tagsAlias')}; $pk = $tagsTable->getPrimaryKey(); $df = $tagsTable->getDisplayField(); foreach ($tags as $k => $tag) { $tags[$k] = [ $pk => $tag->{$pk}, $df => $tag->{$df}, ]; } foreach ($untags as $untag) { foreach ($tags as $k => $tag) { if ((empty($untag[$pk]) || $tag[$pk] === $untag[$pk]) && (empty($untag[$df]) || $tag[$df] === $untag[$df]) ) { unset($tags[$k]); } } } return $this->_updateTags( array_map( function ($i) { return implode(':', $i); }, $tags ), 'replace' ); }
php
public function untag($tags = null) { if (empty($tags)) { return $this->_updateTags([], 'replace'); } $table = TableRegistry::getTableLocator()->get($this->source()); $behavior = $table->behaviors()->Tag; $assoc = $table->getAssociation($behavior->getConfig('tagsAlias')); $property = $assoc->getProperty(); $id = $this->get($table->getPrimaryKey()); $untags = $behavior->normalizeTags($tags); $tags = $this->get($property); if (!$tags) { $contain = [$behavior->getConfig('tagsAlias')]; $tags = $table->get($id, compact('contain'))->get($property); } $tagsTable = $table->{$behavior->getConfig('tagsAlias')}; $pk = $tagsTable->getPrimaryKey(); $df = $tagsTable->getDisplayField(); foreach ($tags as $k => $tag) { $tags[$k] = [ $pk => $tag->{$pk}, $df => $tag->{$df}, ]; } foreach ($untags as $untag) { foreach ($tags as $k => $tag) { if ((empty($untag[$pk]) || $tag[$pk] === $untag[$pk]) && (empty($untag[$df]) || $tag[$df] === $untag[$df]) ) { unset($tags[$k]); } } } return $this->_updateTags( array_map( function ($i) { return implode(':', $i); }, $tags ), 'replace' ); }
[ "public", "function", "untag", "(", "$", "tags", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "tags", ")", ")", "{", "return", "$", "this", "->", "_updateTags", "(", "[", "]", ",", "'replace'", ")", ";", "}", "$", "table", "=", "TableRegi...
Untag entity from given tags. @param string|array $tags List of tags as an array or a delimited string (comma by default). If no value is passed all tags will be removed. @return bool|\Cake\ORM\Entity False on failure, entity on success.
[ "Untag", "entity", "from", "given", "tags", "." ]
6fb767375a39829ea348d64b8fd1b0204b9f26ff
https://github.com/UseMuffin/Tags/blob/6fb767375a39829ea348d64b8fd1b0204b9f26ff/src/Model/Entity/TagAwareTrait.php#L28-L77
train
UseMuffin/Tags
src/Model/Entity/TagAwareTrait.php
TagAwareTrait._updateTags
protected function _updateTags($tags, $saveStrategy) { $table = TableRegistry::getTableLocator()->get($this->source()); $behavior = $table->behaviors()->Tag; $assoc = $table->getAssociation($behavior->getConfig('tagsAlias')); $resetStrategy = $assoc->getSaveStrategy(); $assoc->setSaveStrategy($saveStrategy); $table->patchEntity($this, [$assoc->getProperty() => $tags]); $result = $table->save($this); $assoc->setSaveStrategy($resetStrategy); return $result; }
php
protected function _updateTags($tags, $saveStrategy) { $table = TableRegistry::getTableLocator()->get($this->source()); $behavior = $table->behaviors()->Tag; $assoc = $table->getAssociation($behavior->getConfig('tagsAlias')); $resetStrategy = $assoc->getSaveStrategy(); $assoc->setSaveStrategy($saveStrategy); $table->patchEntity($this, [$assoc->getProperty() => $tags]); $result = $table->save($this); $assoc->setSaveStrategy($resetStrategy); return $result; }
[ "protected", "function", "_updateTags", "(", "$", "tags", ",", "$", "saveStrategy", ")", "{", "$", "table", "=", "TableRegistry", "::", "getTableLocator", "(", ")", "->", "get", "(", "$", "this", "->", "source", "(", ")", ")", ";", "$", "behavior", "="...
Tag entity with given tags. @param string|array $tags List of tags as an array or a delimited string (comma by default). @param string $saveStrategy Whether to merge or replace tags. Valid values 'append', 'replace'. @return bool|\Cake\ORM\Entity False on failure, entity on success.
[ "Tag", "entity", "with", "given", "tags", "." ]
6fb767375a39829ea348d64b8fd1b0204b9f26ff
https://github.com/UseMuffin/Tags/blob/6fb767375a39829ea348d64b8fd1b0204b9f26ff/src/Model/Entity/TagAwareTrait.php#L87-L99
train
Domraider/rxnet
src/Rxnet/RabbitMq/RabbitQueue.php
RabbitQueue.get
public function get($queue, $noAck = false) { $promise = $this->channel->get($queue, $noAck); return \Rxnet\fromPromise($promise) ->map(function (Message $message) { return new RabbitMessage($this->channel, $message, $this->serializer); }); }
php
public function get($queue, $noAck = false) { $promise = $this->channel->get($queue, $noAck); return \Rxnet\fromPromise($promise) ->map(function (Message $message) { return new RabbitMessage($this->channel, $message, $this->serializer); }); }
[ "public", "function", "get", "(", "$", "queue", ",", "$", "noAck", "=", "false", ")", "{", "$", "promise", "=", "$", "this", "->", "channel", "->", "get", "(", "$", "queue", ",", "$", "noAck", ")", ";", "return", "\\", "Rxnet", "\\", "fromPromise",...
Pop one element from the queue @param $queue @param bool $noAck @return Observable
[ "Pop", "one", "element", "from", "the", "queue" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/RabbitMq/RabbitQueue.php#L126-L133
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.upload
public function upload($directory, $run_filename, $code_name, $options = array()) { $temp_file = tempnam(sys_get_temp_dir(), 'iron_worker_php'); if (array_key_exists('ignored', $options)) { if (!is_array($options['ignored'])) { $options['ignored'] = [$options['ignored']]; } } else { $options['ignored'] = []; } if (!self::zipDirectory($directory, $temp_file, true, $options['ignored'])) { unlink($temp_file); return false; } unset($options['ignored']); try { $this->postCode($run_filename, $temp_file, $code_name, $options); } catch (\Exception $e) { unlink($temp_file); throw $e; } return true; }
php
public function upload($directory, $run_filename, $code_name, $options = array()) { $temp_file = tempnam(sys_get_temp_dir(), 'iron_worker_php'); if (array_key_exists('ignored', $options)) { if (!is_array($options['ignored'])) { $options['ignored'] = [$options['ignored']]; } } else { $options['ignored'] = []; } if (!self::zipDirectory($directory, $temp_file, true, $options['ignored'])) { unlink($temp_file); return false; } unset($options['ignored']); try { $this->postCode($run_filename, $temp_file, $code_name, $options); } catch (\Exception $e) { unlink($temp_file); throw $e; } return true; }
[ "public", "function", "upload", "(", "$", "directory", ",", "$", "run_filename", ",", "$", "code_name", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "temp_file", "=", "tempnam", "(", "sys_get_temp_dir", "(", ")", ",", "'iron_worker_php'", ...
Zips and uploads your code Shortcut for zipDirectory() + postCode() @param string $directory Directory with worker files @param string $run_filename This file will be launched as worker @param string $code_name Referenceable (unique) name for your worker @param array $options Optional parameters: - "max_concurrency" The maximum number of tasks that should be run in parallel. - "retries" The number of auto-retries of failed task. - "retries_delay" Delay in seconds between retries. - "config" : An arbitrary string (usually YAML or JSON) that, if provided, will be available in a file that your worker can access. File location will be passed in via the -config argument. The config cannot be larger than 64KB in size. - "ignored" The list of files to be excluded from uploading process. @return bool Result of operation @throws \Exception
[ "Zips", "and", "uploads", "your", "code" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L79-L101
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.createZip
public static function createZip($base_dir, $files, $destination, $overwrite = false) { //if the zip file already exists and overwrite is false, return false if (file_exists($destination) && !$overwrite) { return false; } if (!empty($base_dir)) { $base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } //vars $valid_files = array(); //if files were passed in... if (is_array($files)) { //cycle through each file foreach ($files as $file) { //make sure the file exists if (file_exists($base_dir . $file)) { $valid_files[] = $file; } } } if (count($valid_files)) { $zip = new \ZipArchive(); if ($zip->open($destination, $overwrite ? \ZIPARCHIVE::OVERWRITE : \ZIPARCHIVE::CREATE) !== true) { return false; } foreach ($valid_files as $file) { $zip->addFile($base_dir . $file, $file); } $zip->close(); return file_exists($destination); } else { return false; } }
php
public static function createZip($base_dir, $files, $destination, $overwrite = false) { //if the zip file already exists and overwrite is false, return false if (file_exists($destination) && !$overwrite) { return false; } if (!empty($base_dir)) { $base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } //vars $valid_files = array(); //if files were passed in... if (is_array($files)) { //cycle through each file foreach ($files as $file) { //make sure the file exists if (file_exists($base_dir . $file)) { $valid_files[] = $file; } } } if (count($valid_files)) { $zip = new \ZipArchive(); if ($zip->open($destination, $overwrite ? \ZIPARCHIVE::OVERWRITE : \ZIPARCHIVE::CREATE) !== true) { return false; } foreach ($valid_files as $file) { $zip->addFile($base_dir . $file, $file); } $zip->close(); return file_exists($destination); } else { return false; } }
[ "public", "static", "function", "createZip", "(", "$", "base_dir", ",", "$", "files", ",", "$", "destination", ",", "$", "overwrite", "=", "false", ")", "{", "//if the zip file already exists and overwrite is false, return false", "if", "(", "file_exists", "(", "$",...
Creates a zip archive from array of file names Example: <code> IronWorker::createZip(dirname(__FILE__), array('HelloWorld.php'), 'worker.zip', true); </code> @static @param string $base_dir Full path to directory which contain files @param array $files File names, path (both passesed and stored) is relative to $base_dir. Examples: 'worker.php','lib/file.php' @param string $destination Zip file name. @param bool $overwrite Overwite existing file or not. @return bool
[ "Creates", "a", "zip", "archive", "from", "array", "of", "file", "names" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L119-L153
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.zipDirectory
public static function zipDirectory($directory, $destination, $overwrite = false, $ignored = []) { if (!file_exists($directory) || !is_dir($directory)) { return false; } $directory = rtrim($directory, DIRECTORY_SEPARATOR); $files = self::fileNamesRecursive($directory, '', $ignored); if (empty($files)) { return false; } return self::createZip($directory, $files, $destination, $overwrite); }
php
public static function zipDirectory($directory, $destination, $overwrite = false, $ignored = []) { if (!file_exists($directory) || !is_dir($directory)) { return false; } $directory = rtrim($directory, DIRECTORY_SEPARATOR); $files = self::fileNamesRecursive($directory, '', $ignored); if (empty($files)) { return false; } return self::createZip($directory, $files, $destination, $overwrite); }
[ "public", "static", "function", "zipDirectory", "(", "$", "directory", ",", "$", "destination", ",", "$", "overwrite", "=", "false", ",", "$", "ignored", "=", "[", "]", ")", "{", "if", "(", "!", "file_exists", "(", "$", "directory", ")", "||", "!", "...
Creates a zip archive with all files and folders inside specific directory except for the list of ignored files. Example: <code> IronWorker::zipDirectory(dirname(__FILE__)."/worker/", 'worker.zip', true); </code> @static @param string $directory @param string $destination @param bool $overwrite @param array $ignored @return bool
[ "Creates", "a", "zip", "archive", "with", "all", "files", "and", "folders", "inside", "specific", "directory", "except", "for", "the", "list", "of", "ignored", "files", "." ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L170-L184
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.postCode
public function postCode($filename, $zipFilename, $name, $options = array()) { // Add IronWorker functions to the uploaded worker $this->addRunnerToArchive($zipFilename, $filename, $options); $this->setPostHeaders(); $ts = time(); $runtime_type = $this->runtimeFileType($filename); $sendingData = array( "code_name" => $name, "name" => $name, "standalone" => true, "runtime" => $runtime_type, "file_name" => "runner.php", "version" => $this->version, "timestamp" => $ts, "oauth" => $this->token, "class_name" => $name, "options" => array(), "access_key" => $name, ); $sendingData = array_merge($sendingData, $options); $url = "projects/{$this->project_id}/codes"; $post = array( "data" => json_encode($sendingData), ); if ($this->curlEnabled() && version_compare(PHP_VERSION, '5.5.0', '>=')) { $post['file'] = new \CURLFile($zipFilename); } else { $post['file'] = '@' . $zipFilename; } $response = $this->apiCall(self::POST, $url, array(), $post); return self::json_decode($response); }
php
public function postCode($filename, $zipFilename, $name, $options = array()) { // Add IronWorker functions to the uploaded worker $this->addRunnerToArchive($zipFilename, $filename, $options); $this->setPostHeaders(); $ts = time(); $runtime_type = $this->runtimeFileType($filename); $sendingData = array( "code_name" => $name, "name" => $name, "standalone" => true, "runtime" => $runtime_type, "file_name" => "runner.php", "version" => $this->version, "timestamp" => $ts, "oauth" => $this->token, "class_name" => $name, "options" => array(), "access_key" => $name, ); $sendingData = array_merge($sendingData, $options); $url = "projects/{$this->project_id}/codes"; $post = array( "data" => json_encode($sendingData), ); if ($this->curlEnabled() && version_compare(PHP_VERSION, '5.5.0', '>=')) { $post['file'] = new \CURLFile($zipFilename); } else { $post['file'] = '@' . $zipFilename; } $response = $this->apiCall(self::POST, $url, array(), $post); return self::json_decode($response); }
[ "public", "function", "postCode", "(", "$", "filename", ",", "$", "zipFilename", ",", "$", "name", ",", "$", "options", "=", "array", "(", ")", ")", "{", "// Add IronWorker functions to the uploaded worker", "$", "this", "->", "addRunnerToArchive", "(", "$", "...
Uploads your code package @param string $filename This file will be launched as worker @param string $zipFilename zip file containing code to execute @param string $name referenceable (unique) name for your worker @param array $options Optional parameters: - "max_concurrency" The maximum number of tasks that should be run in parallel. - "retries" The number of auto-retries of failed task. - "retries_delay" Delay in seconds between retries. - "config" : An arbitrary string (usually YAML or JSON) that, if provided, will be available in a file that your worker can access. File location will be passed in via the -config argument. The config cannot be larger than 64KB in size. @return mixed
[ "Uploads", "your", "code", "package" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L277-L310
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.downloadCode
public function downloadCode($code_id) { if (empty($code_id)) { throw new \InvalidArgumentException("Please set code_id"); } $url = "projects/{$this->project_id}/codes/$code_id/download"; return $this->apiCall(self::GET, $url); }
php
public function downloadCode($code_id) { if (empty($code_id)) { throw new \InvalidArgumentException("Please set code_id"); } $url = "projects/{$this->project_id}/codes/$code_id/download"; return $this->apiCall(self::GET, $url); }
[ "public", "function", "downloadCode", "(", "$", "code_id", ")", "{", "if", "(", "empty", "(", "$", "code_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Please set code_id\"", ")", ";", "}", "$", "url", "=", "\"projects/{$this->...
Download Code Package @param String $code_id. @throws \InvalidArgumentException @return string zipped file
[ "Download", "Code", "Package" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L320-L327
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.getCodeRevisions
public function getCodeRevisions($code_id, $page = 0, $per_page = 30) { if (empty($code_id)) { throw new \InvalidArgumentException("Please set code_id"); } $params = array( 'page' => $page, 'per_page' => $per_page, ); $this->setJsonHeaders(); $url = "projects/{$this->project_id}/codes/$code_id/revisions"; $res = json_decode($this->apiCall(self::GET, $url, $params)); return $res->revisions; }
php
public function getCodeRevisions($code_id, $page = 0, $per_page = 30) { if (empty($code_id)) { throw new \InvalidArgumentException("Please set code_id"); } $params = array( 'page' => $page, 'per_page' => $per_page, ); $this->setJsonHeaders(); $url = "projects/{$this->project_id}/codes/$code_id/revisions"; $res = json_decode($this->apiCall(self::GET, $url, $params)); return $res->revisions; }
[ "public", "function", "getCodeRevisions", "(", "$", "code_id", ",", "$", "page", "=", "0", ",", "$", "per_page", "=", "30", ")", "{", "if", "(", "empty", "(", "$", "code_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Plea...
Get all code revisions @param String $code_id. @param int $page Page. Default is 0, maximum is 100. @param int $per_page The number of tasks to return per page. Default is 30, maximum is 100. @throws \InvalidArgumentException @return array of revisions
[ "Get", "all", "code", "revisions" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L339-L352
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.getSchedules
public function getSchedules($page = 0, $per_page = 30) { $url = "projects/{$this->project_id}/schedules"; $this->setJsonHeaders(); $params = array( 'page' => $page, 'per_page' => $per_page, ); $schedules = self::json_decode($this->apiCall(self::GET, $url, $params)); return $schedules->schedules; }
php
public function getSchedules($page = 0, $per_page = 30) { $url = "projects/{$this->project_id}/schedules"; $this->setJsonHeaders(); $params = array( 'page' => $page, 'per_page' => $per_page, ); $schedules = self::json_decode($this->apiCall(self::GET, $url, $params)); return $schedules->schedules; }
[ "public", "function", "getSchedules", "(", "$", "page", "=", "0", ",", "$", "per_page", "=", "30", ")", "{", "$", "url", "=", "\"projects/{$this->project_id}/schedules\"", ";", "$", "this", "->", "setJsonHeaders", "(", ")", ";", "$", "params", "=", "array"...
Get information about all schedules for project @param int $page @param int $per_page @return mixed
[ "Get", "information", "about", "all", "schedules", "for", "project" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L378-L388
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.getSchedule
public function getSchedule($schedule_id) { if (empty($schedule_id)) { throw new \InvalidArgumentException("Please set schedule_id"); } $this->setJsonHeaders(); $url = "projects/{$this->project_id}/schedules/$schedule_id"; return self::json_decode($this->apiCall(self::GET, $url)); }
php
public function getSchedule($schedule_id) { if (empty($schedule_id)) { throw new \InvalidArgumentException("Please set schedule_id"); } $this->setJsonHeaders(); $url = "projects/{$this->project_id}/schedules/$schedule_id"; return self::json_decode($this->apiCall(self::GET, $url)); }
[ "public", "function", "getSchedule", "(", "$", "schedule_id", ")", "{", "if", "(", "empty", "(", "$", "schedule_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Please set schedule_id\"", ")", ";", "}", "$", "this", "->", "setJso...
Get information about schedule @param string $schedule_id Schedule ID @return mixed @throws \InvalidArgumentException
[ "Get", "information", "about", "schedule" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L397-L406
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.postTask
public function postTask($name, $payload = array(), $options = array()) { $ids = $this->postTasks($name, array($payload), $options); return $ids[0]; }
php
public function postTask($name, $payload = array(), $options = array()) { $ids = $this->postTasks($name, array($payload), $options); return $ids[0]; }
[ "public", "function", "postTask", "(", "$", "name", ",", "$", "payload", "=", "array", "(", ")", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "ids", "=", "$", "this", "->", "postTasks", "(", "$", "name", ",", "array", "(", "$", "...
Queues already uploaded worker @param string $name Package name @param array $payload Payload for task @param array $options Optional parameters: - "priority" priority queue to run the job in (0, 1, 2). 0 is default. - "timeout" maximum runtime of your task in seconds. Maximum time is 3600 seconds (60 minutes). Default is 3600 seconds (60 minutes). - "delay" delay before actually queueing the task in seconds. Default is 0 seconds. @return string Created Task ID
[ "Queues", "already", "uploaded", "worker" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L474-L479
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.postTasks
public function postTasks($name, $payloads = array(), $options = array()) { $url = "projects/{$this->project_id}/tasks"; $request = array( 'tasks' => array(), ); foreach ($payloads as $payload) { $task_data = array( "name" => $name, "code_name" => $name, 'payload' => json_encode($payload), ); foreach ($options as $k => $v) { $task_data[$k] = $v; } $request['tasks'][] = $task_data; } $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); $tasks = self::json_decode($res); $ids = array(); foreach ($tasks->tasks as $task) { $ids[] = $task->id; } return $ids; }
php
public function postTasks($name, $payloads = array(), $options = array()) { $url = "projects/{$this->project_id}/tasks"; $request = array( 'tasks' => array(), ); foreach ($payloads as $payload) { $task_data = array( "name" => $name, "code_name" => $name, 'payload' => json_encode($payload), ); foreach ($options as $k => $v) { $task_data[$k] = $v; } $request['tasks'][] = $task_data; } $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); $tasks = self::json_decode($res); $ids = array(); foreach ($tasks->tasks as $task) { $ids[] = $task->id; } return $ids; }
[ "public", "function", "postTasks", "(", "$", "name", ",", "$", "payloads", "=", "array", "(", ")", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "url", "=", "\"projects/{$this->project_id}/tasks\"", ";", "$", "request", "=", "array", "(", ...
Queues many tasks at a time @param string $name Package name @param array $payloads. Each payload will be converted to separate task @param array $options same as postTask() @return array IDs
[ "Queues", "many", "tasks", "at", "a", "time" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L489-L521
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.cancelTask
public function cancelTask($task_id) { if (empty($task_id)) { throw new \InvalidArgumentException("Please set task_id"); } $url = "projects/{$this->project_id}/tasks/$task_id/cancel"; $request = array(); $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); return self::json_decode($res); }
php
public function cancelTask($task_id) { if (empty($task_id)) { throw new \InvalidArgumentException("Please set task_id"); } $url = "projects/{$this->project_id}/tasks/$task_id/cancel"; $request = array(); $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); return self::json_decode($res); }
[ "public", "function", "cancelTask", "(", "$", "task_id", ")", "{", "if", "(", "empty", "(", "$", "task_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Please set task_id\"", ")", ";", "}", "$", "url", "=", "\"projects/{$this->pr...
Cancels task. @param string $task_id Task ID @return mixed @throws \InvalidArgumentException
[ "Cancels", "task", "." ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L552-L563
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.retryTask
public function retryTask($task_id, $delay = 1) { if (empty($task_id)) { throw new \InvalidArgumentException("Please set task_id"); } $url = "projects/{$this->project_id}/tasks/$task_id/retry"; $request = array('delay' => $delay); $this->setCommonHeaders(); $res = json_decode($this->apiCall(self::POST, $url, $request)); return $res->tasks[0]->id; }
php
public function retryTask($task_id, $delay = 1) { if (empty($task_id)) { throw new \InvalidArgumentException("Please set task_id"); } $url = "projects/{$this->project_id}/tasks/$task_id/retry"; $request = array('delay' => $delay); $this->setCommonHeaders(); $res = json_decode($this->apiCall(self::POST, $url, $request)); return $res->tasks[0]->id; }
[ "public", "function", "retryTask", "(", "$", "task_id", ",", "$", "delay", "=", "1", ")", "{", "if", "(", "empty", "(", "$", "task_id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Please set task_id\"", ")", ";", "}", "$", ...
Retry task. @param string $task_id Task ID @param int $delay The number of seconds the task should be delayed before it runs again. @return string Retried Task ID @throws \InvalidArgumentException
[ "Retry", "task", "." ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L573-L584
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.waitFor
public function waitFor($task_id, $sleep = 5, $max_wait_time = 0) { while (1) { $details = $this->getTaskDetails($task_id); if ($details->status != 'queued' && $details->status != 'running') { return $details; } if ($max_wait_time > 0) { $max_wait_time -= $sleep; if ($max_wait_time <= 0) { return false; } } sleep($sleep); } return false; }
php
public function waitFor($task_id, $sleep = 5, $max_wait_time = 0) { while (1) { $details = $this->getTaskDetails($task_id); if ($details->status != 'queued' && $details->status != 'running') { return $details; } if ($max_wait_time > 0) { $max_wait_time -= $sleep; if ($max_wait_time <= 0) { return false; } } sleep($sleep); } return false; }
[ "public", "function", "waitFor", "(", "$", "task_id", ",", "$", "sleep", "=", "5", ",", "$", "max_wait_time", "=", "0", ")", "{", "while", "(", "1", ")", "{", "$", "details", "=", "$", "this", "->", "getTaskDetails", "(", "$", "task_id", ")", ";", ...
Wait while the task specified by task_id executes @param string $task_id Task ID @param int $sleep Delay between API invocations in seconds @param int $max_wait_time Maximum waiting time in seconds, 0 for infinity @return mixed $details Task details or false
[ "Wait", "while", "the", "task", "specified", "by", "task_id", "executes" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L606-L624
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.postSchedule
public function postSchedule($name, $options, $payload = array()) { $url = "projects/{$this->project_id}/schedules"; $shedule = array( 'name' => $name, 'code_name' => $name, 'payload' => json_encode($payload), ); $request = array( 'schedules' => array( array_merge($shedule, $options), ), ); $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); $shedules = self::json_decode($res); return $shedules->schedules[0]->id; }
php
public function postSchedule($name, $options, $payload = array()) { $url = "projects/{$this->project_id}/schedules"; $shedule = array( 'name' => $name, 'code_name' => $name, 'payload' => json_encode($payload), ); $request = array( 'schedules' => array( array_merge($shedule, $options), ), ); $this->setCommonHeaders(); $res = $this->apiCall(self::POST, $url, $request); $shedules = self::json_decode($res); return $shedules->schedules[0]->id; }
[ "public", "function", "postSchedule", "(", "$", "name", ",", "$", "options", ",", "$", "payload", "=", "array", "(", ")", ")", "{", "$", "url", "=", "\"projects/{$this->project_id}/schedules\"", ";", "$", "shedule", "=", "array", "(", "'name'", "=>", "$", ...
Schedule a task @param string $name @param array $options options contain: start_at OR delay — required - start_at is time of first run. Delay is number of seconds to wait before starting. run_every — optional - Time in seconds between runs. If omitted, task will only run once. end_at — optional - Time tasks will stop being enqueued. (Should be a Time or DateTime object.) run_times — optional - Number of times to run task. For example, if run_times: is 5, the task will run 5 times. priority — optional - Priority queue to run the job in (0, 1, 2). p0 is default. Running at higher priorities to reduce time jobs may spend in the queue, once they come off schedule. Same as priority when queuing up a task. @param array $payload @return mixed
[ "Schedule", "a", "task" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L643-L661
train
iron-io/iron_worker_php
src/IronWorker.php
IronWorker.workerHeader
private function workerHeader($worker_file_name, $envs = array()) { $export_env = ""; foreach ($envs as $env => $value) { $export_env .= "putenv(\"$env=$value\");\r\n"; } $header = <<<EOL <?php /*IRON_WORKER_HEADER*/ $export_env function getArgs(\$assoc = true) { global \$argv; \$args = array('task_id' => null, 'dir' => null, 'payload' => array(), 'config' => null); foreach (\$argv as \$k => \$v) { if (empty(\$argv[\$k + 1])) { continue; } if (\$v == '-id') \$args['task_id'] = \$argv[\$k + 1]; if (\$v == '-d') \$args['dir'] = \$argv[\$k + 1]; if (\$v == '-payload') \$args['payload_file'] = \$argv[\$k + 1]; if (\$v == '-config') \$args['config_file'] = \$argv[\$k + 1]; } if (getenv('TASK_ID')) \$args['task_id'] = getenv('TASK_ID'); if (getenv('TASK_DIR')) \$args['dir'] = getenv('TASK_DIR'); if (getenv('PAYLOAD_FILE')) \$args['payload_file'] = getenv('PAYLOAD_FILE'); if (getenv('CONFIG_FILE')) \$args['config_file'] = getenv('CONFIG_FILE'); if (array_key_exists('payload_file',\$args) && file_exists(\$args['payload_file'])) { \$args['payload'] = file_get_contents(\$args['payload_file']); \$parsed_payload = json_decode(\$args['payload'], \$assoc); if (\$parsed_payload != null) { \$args['payload'] = \$parsed_payload; } } if (array_key_exists('config_file',\$args) && file_exists(\$args['config_file'])) { \$args['config'] = file_get_contents(\$args['config_file']); \$parsed_config = json_decode(\$args['config'], \$assoc); if (\$parsed_config != null) { \$args['config'] = \$parsed_config; } } return \$args; } function getPayload(\$assoc = false) { \$args = getArgs(\$assoc); return \$args['payload']; } function getConfig(\$assoc = true) { \$args = getArgs(\$assoc); return \$args['config']; } require dirname(__FILE__)."/[SCRIPT]"; EOL; $header = str_replace( array('[PROJECT_ID]', '[URL]', '[HEADERS]', '[SCRIPT]'), array($this->project_id, $this->url, var_export($this->compiledHeaders(), true), $worker_file_name), $header ); return trim($header, " \n\r"); }
php
private function workerHeader($worker_file_name, $envs = array()) { $export_env = ""; foreach ($envs as $env => $value) { $export_env .= "putenv(\"$env=$value\");\r\n"; } $header = <<<EOL <?php /*IRON_WORKER_HEADER*/ $export_env function getArgs(\$assoc = true) { global \$argv; \$args = array('task_id' => null, 'dir' => null, 'payload' => array(), 'config' => null); foreach (\$argv as \$k => \$v) { if (empty(\$argv[\$k + 1])) { continue; } if (\$v == '-id') \$args['task_id'] = \$argv[\$k + 1]; if (\$v == '-d') \$args['dir'] = \$argv[\$k + 1]; if (\$v == '-payload') \$args['payload_file'] = \$argv[\$k + 1]; if (\$v == '-config') \$args['config_file'] = \$argv[\$k + 1]; } if (getenv('TASK_ID')) \$args['task_id'] = getenv('TASK_ID'); if (getenv('TASK_DIR')) \$args['dir'] = getenv('TASK_DIR'); if (getenv('PAYLOAD_FILE')) \$args['payload_file'] = getenv('PAYLOAD_FILE'); if (getenv('CONFIG_FILE')) \$args['config_file'] = getenv('CONFIG_FILE'); if (array_key_exists('payload_file',\$args) && file_exists(\$args['payload_file'])) { \$args['payload'] = file_get_contents(\$args['payload_file']); \$parsed_payload = json_decode(\$args['payload'], \$assoc); if (\$parsed_payload != null) { \$args['payload'] = \$parsed_payload; } } if (array_key_exists('config_file',\$args) && file_exists(\$args['config_file'])) { \$args['config'] = file_get_contents(\$args['config_file']); \$parsed_config = json_decode(\$args['config'], \$assoc); if (\$parsed_config != null) { \$args['config'] = \$parsed_config; } } return \$args; } function getPayload(\$assoc = false) { \$args = getArgs(\$assoc); return \$args['payload']; } function getConfig(\$assoc = true) { \$args = getArgs(\$assoc); return \$args['config']; } require dirname(__FILE__)."/[SCRIPT]"; EOL; $header = str_replace( array('[PROJECT_ID]', '[URL]', '[HEADERS]', '[SCRIPT]'), array($this->project_id, $this->url, var_export($this->compiledHeaders(), true), $worker_file_name), $header ); return trim($header, " \n\r"); }
[ "private", "function", "workerHeader", "(", "$", "worker_file_name", ",", "$", "envs", "=", "array", "(", ")", ")", "{", "$", "export_env", "=", "\"\"", ";", "foreach", "(", "$", "envs", "as", "$", "env", "=>", "$", "value", ")", "{", "$", "export_en...
Contain php code that adds to worker before upload @param string $worker_file_name @param array $envs @return string
[ "Contain", "php", "code", "that", "adds", "to", "worker", "before", "upload" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/IronWorker.php#L800-L883
train
iron-io/iron_worker_php
src/Runtime.php
Runtime.getArgs
public static function getArgs($assoc = true) { global $argv; $args = array('task_id' => null, 'dir' => null, 'payload' => array(), 'config' => null); foreach ($argv as $k => $v) { if (empty($argv[$k + 1])) { continue; } if ($v == '-id') { $args['task_id'] = $argv[$k + 1]; } if ($v == '-d') { $args['dir'] = $argv[$k + 1]; } if ($v == '-payload') { $args['payload_file'] = $argv[$k + 1]; } if ($v == '-config') { $args['config_file'] = $argv[$k + 1]; } } if (getenv('TASK_ID')) { $args['task_id'] = getenv('TASK_ID'); } if (getenv('TASK_DIR')) { $args['dir'] = getenv('TASK_DIR'); } if (getenv('PAYLOAD_FILE')) { $args['payload_file'] = getenv('PAYLOAD_FILE'); } if (getenv('CONFIG_FILE')) { $args['config_file'] = getenv('CONFIG_FILE'); } if (array_key_exists('payload_file', $args) && file_exists($args['payload_file'])) { $args['payload'] = file_get_contents($args['payload_file']); $parsed_payload = json_decode($args['payload'], $assoc); if ($parsed_payload != null) { $args['payload'] = $parsed_payload; } } if (array_key_exists('config_file', $args) && file_exists($args['config_file'])) { $args['config'] = file_get_contents($args['config_file']); $parsed_config = json_decode($args['config'], $assoc); if ($parsed_config != null) { $args['config'] = $parsed_config; } } return $args; }
php
public static function getArgs($assoc = true) { global $argv; $args = array('task_id' => null, 'dir' => null, 'payload' => array(), 'config' => null); foreach ($argv as $k => $v) { if (empty($argv[$k + 1])) { continue; } if ($v == '-id') { $args['task_id'] = $argv[$k + 1]; } if ($v == '-d') { $args['dir'] = $argv[$k + 1]; } if ($v == '-payload') { $args['payload_file'] = $argv[$k + 1]; } if ($v == '-config') { $args['config_file'] = $argv[$k + 1]; } } if (getenv('TASK_ID')) { $args['task_id'] = getenv('TASK_ID'); } if (getenv('TASK_DIR')) { $args['dir'] = getenv('TASK_DIR'); } if (getenv('PAYLOAD_FILE')) { $args['payload_file'] = getenv('PAYLOAD_FILE'); } if (getenv('CONFIG_FILE')) { $args['config_file'] = getenv('CONFIG_FILE'); } if (array_key_exists('payload_file', $args) && file_exists($args['payload_file'])) { $args['payload'] = file_get_contents($args['payload_file']); $parsed_payload = json_decode($args['payload'], $assoc); if ($parsed_payload != null) { $args['payload'] = $parsed_payload; } } if (array_key_exists('config_file', $args) && file_exists($args['config_file'])) { $args['config'] = file_get_contents($args['config_file']); $parsed_config = json_decode($args['config'], $assoc); if ($parsed_config != null) { $args['config'] = $parsed_config; } } return $args; }
[ "public", "static", "function", "getArgs", "(", "$", "assoc", "=", "true", ")", "{", "global", "$", "argv", ";", "$", "args", "=", "array", "(", "'task_id'", "=>", "null", ",", "'dir'", "=>", "null", ",", "'payload'", "=>", "array", "(", ")", ",", ...
getArgs gets the arguments from the input to this worker
[ "getArgs", "gets", "the", "arguments", "from", "the", "input", "to", "this", "worker" ]
fc2dec05a00a4fa1da189511a4933c5c5e447352
https://github.com/iron-io/iron_worker_php/blob/fc2dec05a00a4fa1da189511a4933c5c5e447352/src/Runtime.php#L33-L99
train
freearhey/knowledge-graph
src/KnowledgeGraph.php
KnowledgeGraph.search
public function search($query, $type = null, $lang = null, $limit = null) { $results = $this->client->request([ 'query' => $query, 'types' => $type, 'languages' => $lang, 'limit' => $limit ]); return $results; }
php
public function search($query, $type = null, $lang = null, $limit = null) { $results = $this->client->request([ 'query' => $query, 'types' => $type, 'languages' => $lang, 'limit' => $limit ]); return $results; }
[ "public", "function", "search", "(", "$", "query", ",", "$", "type", "=", "null", ",", "$", "lang", "=", "null", ",", "$", "limit", "=", "null", ")", "{", "$", "results", "=", "$", "this", "->", "client", "->", "request", "(", "[", "'query'", "=>...
Search by entity name @param string $query @param string $type Restricts returned results to those of the specified types. (e.g. "Person") @param string $lang Language code (ISO 639) to run the query with (e.g. "es") @param string $limit Limits the number of results to be returned. (default: 20) @return \Illuminate\Support\Collection Return collection of \KnowledgeGraph\SearchResult
[ "Search", "by", "entity", "name" ]
62eadb4bb2cdf97a14de2b4973d8aa361411e21a
https://github.com/freearhey/knowledge-graph/blob/62eadb4bb2cdf97a14de2b4973d8aa361411e21a/src/KnowledgeGraph.php#L30-L40
train
Domraider/rxnet
src/Rxnet/RabbitMq/RabbitMq.php
RabbitMq.channel
public function channel($bind = []) { if (!is_array($bind)) { $bind = func_get_args(); } return $this->bunny->connect() ->flatMap(function () { return $this->bunny->channel(); }) ->map(function (Channel $channel) use ($bind) { foreach ($bind as $obj) { $obj->setChannel($channel); } return $channel; }); }
php
public function channel($bind = []) { if (!is_array($bind)) { $bind = func_get_args(); } return $this->bunny->connect() ->flatMap(function () { return $this->bunny->channel(); }) ->map(function (Channel $channel) use ($bind) { foreach ($bind as $obj) { $obj->setChannel($channel); } return $channel; }); }
[ "public", "function", "channel", "(", "$", "bind", "=", "[", "]", ")", "{", "if", "(", "!", "is_array", "(", "$", "bind", ")", ")", "{", "$", "bind", "=", "func_get_args", "(", ")", ";", "}", "return", "$", "this", "->", "bunny", "->", "connect",...
Open a new channel and attribute it to given queues or exchanges @param RabbitQueue[]|RabbitExchange[] $bind @return Observable\AnonymousObservable
[ "Open", "a", "new", "channel", "and", "attribute", "it", "to", "given", "queues", "or", "exchanges" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/RabbitMq/RabbitMq.php#L73-L88
train
Domraider/rxnet
src/Rxnet/RabbitMq/RabbitMq.php
RabbitMq.consume
public function consume($queue, $prefetchCount = null, $prefetchSize = null, $consumerId = null, $opts = []) { return $this->channel() ->doOnNext(function (Channel $channel) use ($prefetchCount, $prefetchSize) { $channel->qos($prefetchSize, $prefetchCount); }) ->flatMap( function (Channel $channel) use ($queue, $consumerId, $opts) { return $this->queue($queue, $opts, $channel) ->consume($consumerId); } ); }
php
public function consume($queue, $prefetchCount = null, $prefetchSize = null, $consumerId = null, $opts = []) { return $this->channel() ->doOnNext(function (Channel $channel) use ($prefetchCount, $prefetchSize) { $channel->qos($prefetchSize, $prefetchCount); }) ->flatMap( function (Channel $channel) use ($queue, $consumerId, $opts) { return $this->queue($queue, $opts, $channel) ->consume($consumerId); } ); }
[ "public", "function", "consume", "(", "$", "queue", ",", "$", "prefetchCount", "=", "null", ",", "$", "prefetchSize", "=", "null", ",", "$", "consumerId", "=", "null", ",", "$", "opts", "=", "[", "]", ")", "{", "return", "$", "this", "->", "channel",...
Consume given queue at @param string $queue name of the queue @param int|null $prefetchCount @param int|null $prefetchSize @param string $consumerId @param array $opts @return Observable\AnonymousObservable
[ "Consume", "given", "queue", "at" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/RabbitMq/RabbitMq.php#L99-L111
train
Domraider/rxnet
src/Rxnet/RabbitMq/RabbitMq.php
RabbitMq.produce
public function produce($data, $headers = [], $exchange = '', $routingKey) { return Observable::create(function (ObserverInterface $observer) use ($exchange, $data, $headers, $routingKey) { return $this->channel() ->flatMap( function (Channel $channel) use ($exchange, $data, $headers, $routingKey) { return $this->exchange($exchange, [], $channel) ->produce($data, $routingKey, $headers) ->doOnNext(function () use ($channel) { $channel->close(); }); } )->subscribe($observer); }); }
php
public function produce($data, $headers = [], $exchange = '', $routingKey) { return Observable::create(function (ObserverInterface $observer) use ($exchange, $data, $headers, $routingKey) { return $this->channel() ->flatMap( function (Channel $channel) use ($exchange, $data, $headers, $routingKey) { return $this->exchange($exchange, [], $channel) ->produce($data, $routingKey, $headers) ->doOnNext(function () use ($channel) { $channel->close(); }); } )->subscribe($observer); }); }
[ "public", "function", "produce", "(", "$", "data", ",", "$", "headers", "=", "[", "]", ",", "$", "exchange", "=", "''", ",", "$", "routingKey", ")", "{", "return", "Observable", "::", "create", "(", "function", "(", "ObserverInterface", "$", "observer", ...
One time produce on dedicated channel and close after @param $data @param array $headers @param string $exchange @param $routingKey @return Observable\AnonymousObservable
[ "One", "time", "produce", "on", "dedicated", "channel", "and", "close", "after" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/RabbitMq/RabbitMq.php#L121-L135
train
UseMuffin/Tags
src/Model/Behavior/TagBehavior.php
TagBehavior.bindAssociations
public function bindAssociations() { $config = $this->getConfig(); $tagsAlias = $config['tagsAlias']; $tagsAssoc = $config['tagsAssoc']; $taggedAlias = $config['taggedAlias']; $taggedAssoc = $config['taggedAssoc']; $table = $this->_table; $tableAlias = $this->_table->getAlias(); $assocConditions = [$taggedAlias . '.' . $this->getConfig('fkTableField') => $table->getTable()]; if (!$table->hasAssociation($taggedAlias)) { $table->hasMany($taggedAlias, $taggedAssoc + [ 'foreignKey' => $tagsAssoc['foreignKey'], 'conditions' => $assocConditions, ]); } if (!$table->hasAssociation($tagsAlias)) { $table->belongsToMany($tagsAlias, $tagsAssoc + [ 'through' => $table->{$taggedAlias}->getTarget(), 'conditions' => $assocConditions, ]); } if (!$table->{$tagsAlias}->hasAssociation($tableAlias)) { $table->{$tagsAlias} ->belongsToMany($tableAlias, [ 'className' => $table->getTable(), ] + $tagsAssoc); } if (!$table->{$taggedAlias}->hasAssociation($tableAlias)) { $table->{$taggedAlias} ->belongsTo($tableAlias, [ 'className' => $table->getTable(), 'foreignKey' => $tagsAssoc['foreignKey'], 'conditions' => $assocConditions, 'joinType' => 'INNER', ]); } if (!$table->{$taggedAlias}->hasAssociation($tableAlias . $tagsAlias)) { $table->{$taggedAlias} ->belongsTo($tableAlias . $tagsAlias, [ 'className' => $tagsAssoc['className'], 'foreignKey' => $tagsAssoc['targetForeignKey'], 'conditions' => $assocConditions, 'joinType' => 'INNER', ]); } }
php
public function bindAssociations() { $config = $this->getConfig(); $tagsAlias = $config['tagsAlias']; $tagsAssoc = $config['tagsAssoc']; $taggedAlias = $config['taggedAlias']; $taggedAssoc = $config['taggedAssoc']; $table = $this->_table; $tableAlias = $this->_table->getAlias(); $assocConditions = [$taggedAlias . '.' . $this->getConfig('fkTableField') => $table->getTable()]; if (!$table->hasAssociation($taggedAlias)) { $table->hasMany($taggedAlias, $taggedAssoc + [ 'foreignKey' => $tagsAssoc['foreignKey'], 'conditions' => $assocConditions, ]); } if (!$table->hasAssociation($tagsAlias)) { $table->belongsToMany($tagsAlias, $tagsAssoc + [ 'through' => $table->{$taggedAlias}->getTarget(), 'conditions' => $assocConditions, ]); } if (!$table->{$tagsAlias}->hasAssociation($tableAlias)) { $table->{$tagsAlias} ->belongsToMany($tableAlias, [ 'className' => $table->getTable(), ] + $tagsAssoc); } if (!$table->{$taggedAlias}->hasAssociation($tableAlias)) { $table->{$taggedAlias} ->belongsTo($tableAlias, [ 'className' => $table->getTable(), 'foreignKey' => $tagsAssoc['foreignKey'], 'conditions' => $assocConditions, 'joinType' => 'INNER', ]); } if (!$table->{$taggedAlias}->hasAssociation($tableAlias . $tagsAlias)) { $table->{$taggedAlias} ->belongsTo($tableAlias . $tagsAlias, [ 'className' => $tagsAssoc['className'], 'foreignKey' => $tagsAssoc['targetForeignKey'], 'conditions' => $assocConditions, 'joinType' => 'INNER', ]); } }
[ "public", "function", "bindAssociations", "(", ")", "{", "$", "config", "=", "$", "this", "->", "getConfig", "(", ")", ";", "$", "tagsAlias", "=", "$", "config", "[", "'tagsAlias'", "]", ";", "$", "tagsAssoc", "=", "$", "config", "[", "'tagsAssoc'", "]...
Binds all required associations if an association of the same name has not already been configured. @return void
[ "Binds", "all", "required", "associations", "if", "an", "association", "of", "the", "same", "name", "has", "not", "already", "been", "configured", "." ]
6fb767375a39829ea348d64b8fd1b0204b9f26ff
https://github.com/UseMuffin/Tags/blob/6fb767375a39829ea348d64b8fd1b0204b9f26ff/src/Model/Behavior/TagBehavior.php#L98-L151
train
UseMuffin/Tags
src/Model/Behavior/TagBehavior.php
TagBehavior.attachCounters
public function attachCounters() { $config = $this->getConfig(); $tagsAlias = $config['tagsAlias']; $taggedAlias = $config['taggedAlias']; $taggedTable = $this->_table->{$taggedAlias}; if (!$taggedTable->hasBehavior('CounterCache')) { $taggedTable->addBehavior('CounterCache'); } $counterCache = $taggedTable->behaviors()->CounterCache; if (!$counterCache->getConfig($tagsAlias)) { $counterCache->setConfig($tagsAlias, $config['tagsCounter']); } if ($config['taggedCounter'] === false) { return; } foreach ($config['taggedCounter'] as $field => $o) { if (!$this->_table->hasField($field)) { throw new RuntimeException(sprintf( 'Field "%s" does not exist in table "%s"', $field, $this->_table->getTable() )); } } if (!$counterCache->getConfig($taggedAlias)) { $field = key($config['taggedCounter']); $config['taggedCounter']['tag_count']['conditions'] = [ $taggedTable->aliasField($this->getConfig('fkTableField')) => $this->_table->getTable(), ]; $counterCache->setConfig($this->_table->getAlias(), $config['taggedCounter']); } }
php
public function attachCounters() { $config = $this->getConfig(); $tagsAlias = $config['tagsAlias']; $taggedAlias = $config['taggedAlias']; $taggedTable = $this->_table->{$taggedAlias}; if (!$taggedTable->hasBehavior('CounterCache')) { $taggedTable->addBehavior('CounterCache'); } $counterCache = $taggedTable->behaviors()->CounterCache; if (!$counterCache->getConfig($tagsAlias)) { $counterCache->setConfig($tagsAlias, $config['tagsCounter']); } if ($config['taggedCounter'] === false) { return; } foreach ($config['taggedCounter'] as $field => $o) { if (!$this->_table->hasField($field)) { throw new RuntimeException(sprintf( 'Field "%s" does not exist in table "%s"', $field, $this->_table->getTable() )); } } if (!$counterCache->getConfig($taggedAlias)) { $field = key($config['taggedCounter']); $config['taggedCounter']['tag_count']['conditions'] = [ $taggedTable->aliasField($this->getConfig('fkTableField')) => $this->_table->getTable(), ]; $counterCache->setConfig($this->_table->getAlias(), $config['taggedCounter']); } }
[ "public", "function", "attachCounters", "(", ")", "{", "$", "config", "=", "$", "this", "->", "getConfig", "(", ")", ";", "$", "tagsAlias", "=", "$", "config", "[", "'tagsAlias'", "]", ";", "$", "taggedAlias", "=", "$", "config", "[", "'taggedAlias'", ...
Attaches the `CounterCache` behavior to the `Tagged` table to keep counts on both the `Tags` and the tagged entities. @return void @throws \RuntimeException If configured counter cache field does not exist in table.
[ "Attaches", "the", "CounterCache", "behavior", "to", "the", "Tagged", "table", "to", "keep", "counts", "on", "both", "the", "Tags", "and", "the", "tagged", "entities", "." ]
6fb767375a39829ea348d64b8fd1b0204b9f26ff
https://github.com/UseMuffin/Tags/blob/6fb767375a39829ea348d64b8fd1b0204b9f26ff/src/Model/Behavior/TagBehavior.php#L160-L199
train
freearhey/knowledge-graph
src/Client.php
Client.request
public function request($params) { $query = array_merge($params, [ 'key' => $this->key ]); try { $response = $this->client->get(self::API_ENDPOINT, [ 'query' => $query ]); } catch (ClientException $exception) { return collect([]); } $results = json_decode($response->getBody(), true); $output = []; for($i = 0; $i < count($results['itemListElement']); $i++) { $output[] = new SearchResult($results['itemListElement'][$i]); } return collect($output); }
php
public function request($params) { $query = array_merge($params, [ 'key' => $this->key ]); try { $response = $this->client->get(self::API_ENDPOINT, [ 'query' => $query ]); } catch (ClientException $exception) { return collect([]); } $results = json_decode($response->getBody(), true); $output = []; for($i = 0; $i < count($results['itemListElement']); $i++) { $output[] = new SearchResult($results['itemListElement'][$i]); } return collect($output); }
[ "public", "function", "request", "(", "$", "params", ")", "{", "$", "query", "=", "array_merge", "(", "$", "params", ",", "[", "'key'", "=>", "$", "this", "->", "key", "]", ")", ";", "try", "{", "$", "response", "=", "$", "this", "->", "client", ...
Make request to Knowledge Graph API @var array $params @return \Illuminate\Support\Collection Return collection of \KnowledgeGraph\Result
[ "Make", "request", "to", "Knowledge", "Graph", "API" ]
62eadb4bb2cdf97a14de2b4973d8aa361411e21a
https://github.com/freearhey/knowledge-graph/blob/62eadb4bb2cdf97a14de2b4973d8aa361411e21a/src/Client.php#L44-L71
train
joomla-framework/archive
src/Zip.php
Zip.extractCustom
protected function extractCustom($archive, $destination) { $this->data = null; $this->metadata = null; $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } if (!$this->readZipInfo($this->data)) { throw new \RuntimeException('Get ZIP Information failed'); } for ($i = 0, $n = \count($this->metadata); $i < $n; $i++) { $lastPathCharacter = substr($this->metadata[$i]['name'], -1, 1); if ($lastPathCharacter !== '/' && $lastPathCharacter !== '\\') { $buffer = $this->getFileData($i); $path = Path::clean($destination . '/' . $this->metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(\dirname($path))) { throw new \RuntimeException('Unable to create destination folder ' . \dirname($path)); } if (!File::write($path, $buffer)) { throw new \RuntimeException('Unable to write entry to file ' . $path); } } } return true; }
php
protected function extractCustom($archive, $destination) { $this->data = null; $this->metadata = null; $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } if (!$this->readZipInfo($this->data)) { throw new \RuntimeException('Get ZIP Information failed'); } for ($i = 0, $n = \count($this->metadata); $i < $n; $i++) { $lastPathCharacter = substr($this->metadata[$i]['name'], -1, 1); if ($lastPathCharacter !== '/' && $lastPathCharacter !== '\\') { $buffer = $this->getFileData($i); $path = Path::clean($destination . '/' . $this->metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(\dirname($path))) { throw new \RuntimeException('Unable to create destination folder ' . \dirname($path)); } if (!File::write($path, $buffer)) { throw new \RuntimeException('Unable to write entry to file ' . $path); } } } return true; }
[ "protected", "function", "extractCustom", "(", "$", "archive", ",", "$", "destination", ")", "{", "$", "this", "->", "data", "=", "null", ";", "$", "this", "->", "metadata", "=", "null", ";", "$", "this", "->", "data", "=", "file_get_contents", "(", "$...
Extract a ZIP compressed file to a given path using a php based algorithm that only requires zlib support @param string $archive Path to ZIP archive to extract. @param string $destination Path to extract archive into. @return boolean True if successful @since 1.0 @throws \RuntimeException
[ "Extract", "a", "ZIP", "compressed", "file", "to", "a", "given", "path", "using", "a", "php", "based", "algorithm", "that", "only", "requires", "zlib", "support" ]
b1d496e8c7814f1e376cb14296c38d5ef4e08c78
https://github.com/joomla-framework/archive/blob/b1d496e8c7814f1e376cb14296c38d5ef4e08c78/src/Zip.php#L223-L263
train
joomla-framework/archive
src/Zip.php
Zip.extractNative
protected function extractNative($archive, $destination) { $zip = zip_open($archive); if (!\is_resource($zip)) { throw new \RuntimeException('Unable to open archive'); } // Make sure the destination folder exists if (!Folder::create($destination)) { throw new \RuntimeException('Unable to create destination folder ' . \dirname($path)); } // Read files in the archive while ($file = @zip_read($zip)) { if (!zip_entry_open($zip, $file, 'r')) { throw new \RuntimeException('Unable to read ZIP entry'); } if (substr(zip_entry_name($file), \strlen(zip_entry_name($file)) - 1) != '/') { $buffer = zip_entry_read($file, zip_entry_filesize($file)); if (File::write($destination . '/' . zip_entry_name($file), $buffer) === false) { throw new \RuntimeException('Unable to write ZIP entry to file ' . $destination . '/' . zip_entry_name($file)); } zip_entry_close($file); } } @zip_close($zip); return true; }
php
protected function extractNative($archive, $destination) { $zip = zip_open($archive); if (!\is_resource($zip)) { throw new \RuntimeException('Unable to open archive'); } // Make sure the destination folder exists if (!Folder::create($destination)) { throw new \RuntimeException('Unable to create destination folder ' . \dirname($path)); } // Read files in the archive while ($file = @zip_read($zip)) { if (!zip_entry_open($zip, $file, 'r')) { throw new \RuntimeException('Unable to read ZIP entry'); } if (substr(zip_entry_name($file), \strlen(zip_entry_name($file)) - 1) != '/') { $buffer = zip_entry_read($file, zip_entry_filesize($file)); if (File::write($destination . '/' . zip_entry_name($file), $buffer) === false) { throw new \RuntimeException('Unable to write ZIP entry to file ' . $destination . '/' . zip_entry_name($file)); } zip_entry_close($file); } } @zip_close($zip); return true; }
[ "protected", "function", "extractNative", "(", "$", "archive", ",", "$", "destination", ")", "{", "$", "zip", "=", "zip_open", "(", "$", "archive", ")", ";", "if", "(", "!", "\\", "is_resource", "(", "$", "zip", ")", ")", "{", "throw", "new", "\\", ...
Extract a ZIP compressed file to a given path using native php api calls for speed @param string $archive Path to ZIP archive to extract @param string $destination Path to extract archive into @return boolean True on success @since 1.0 @throws \RuntimeException
[ "Extract", "a", "ZIP", "compressed", "file", "to", "a", "given", "path", "using", "native", "php", "api", "calls", "for", "speed" ]
b1d496e8c7814f1e376cb14296c38d5ef4e08c78
https://github.com/joomla-framework/archive/blob/b1d496e8c7814f1e376cb14296c38d5ef4e08c78/src/Zip.php#L276-L315
train
Domraider/rxnet
src/Rxnet/Contract/DataContainerTrait.php
DataContainerTrait.toStdClass
protected function toStdClass($data) { if (is_array($data) || $data instanceof \ArrayObject) { $data = json_decode(json_encode($data)); } return $data; }
php
protected function toStdClass($data) { if (is_array($data) || $data instanceof \ArrayObject) { $data = json_decode(json_encode($data)); } return $data; }
[ "protected", "function", "toStdClass", "(", "$", "data", ")", "{", "if", "(", "is_array", "(", "$", "data", ")", "||", "$", "data", "instanceof", "\\", "ArrayObject", ")", "{", "$", "data", "=", "json_decode", "(", "json_encode", "(", "$", "data", ")",...
Transform array or array object to json compatible stdClass @param $data @return mixed
[ "Transform", "array", "or", "array", "object", "to", "json", "compatible", "stdClass" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Contract/DataContainerTrait.php#L127-L133
train
Domraider/rxnet
src/Rxnet/Contract/DataContainerTrait.php
DataContainerTrait.normalize
protected function normalize($payload) { $data = get_object_vars($payload); foreach ($data as $k => $v) { if ($v instanceof \DateTime) { $payload->$k = $v->format('c'); continue; } if (is_object($v)) { $payload->$k = $this->normalize($v); continue; } } return $payload; }
php
protected function normalize($payload) { $data = get_object_vars($payload); foreach ($data as $k => $v) { if ($v instanceof \DateTime) { $payload->$k = $v->format('c'); continue; } if (is_object($v)) { $payload->$k = $this->normalize($v); continue; } } return $payload; }
[ "protected", "function", "normalize", "(", "$", "payload", ")", "{", "$", "data", "=", "get_object_vars", "(", "$", "payload", ")", ";", "foreach", "(", "$", "data", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "v", "instanceof", "\\",...
Transform nested sub objects to string if needed Only DateTime or Carbon now @param object $payload @return object
[ "Transform", "nested", "sub", "objects", "to", "string", "if", "needed", "Only", "DateTime", "or", "Carbon", "now" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Contract/DataContainerTrait.php#L141-L155
train
Domraider/rxnet
src/Rxnet/Statsd/Statsd.php
Statsd.timing
public function timing($stat, $time, $sampleRate = 1, array $tags = null) { return $this->send(array($stat => "$time|ms"), $sampleRate, $tags); }
php
public function timing($stat, $time, $sampleRate = 1, array $tags = null) { return $this->send(array($stat => "$time|ms"), $sampleRate, $tags); }
[ "public", "function", "timing", "(", "$", "stat", ",", "$", "time", ",", "$", "sampleRate", "=", "1", ",", "array", "$", "tags", "=", "null", ")", "{", "return", "$", "this", "->", "send", "(", "array", "(", "$", "stat", "=>", "\"$time|ms\"", ")", ...
Log timing information @param string $stat The metric to in log timing info for. @param float $time The ellapsed time (ms) to log @param float|1.0 $sampleRate the rate (0-1) for sampling. @param array|null $tags @return Observable
[ "Log", "timing", "information" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Statsd/Statsd.php#L58-L61
train
Domraider/rxnet
src/Rxnet/Statsd/Statsd.php
Statsd.increment
public function increment($stats, $sampleRate = 1, array $tags = null) { return $this->updateStats($stats, 1, $sampleRate, $tags); }
php
public function increment($stats, $sampleRate = 1, array $tags = null) { return $this->updateStats($stats, 1, $sampleRate, $tags); }
[ "public", "function", "increment", "(", "$", "stats", ",", "$", "sampleRate", "=", "1", ",", "array", "$", "tags", "=", "null", ")", "{", "return", "$", "this", "->", "updateStats", "(", "$", "stats", ",", "1", ",", "$", "sampleRate", ",", "$", "ta...
Increments one or more stats counters @param string|array $stats The metric(s) to increment. @param float|1 $sampleRate the rate (0-1) for sampling. @param array|null $tags @return Observable
[ "Increments", "one", "or", "more", "stats", "counters" ]
1dcbf616dc5999c6ac28b8fd858ab234d2c5e723
https://github.com/Domraider/rxnet/blob/1dcbf616dc5999c6ac28b8fd858ab234d2c5e723/src/Rxnet/Statsd/Statsd.php#L113-L116
train