repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
snowair/phalcon-debugbar
src/PhalconDebugbar.php
PhalconDebugbar.collect
public function collect() { $this->sortCollectors(); /** @var Request $request */ $request = $this->di['request']; $this->data = array( '__meta' => array( 'id' => $this->getCurrentRequestId(), 'datetime' => date('Y-m-d H:i:s'), 'utime' => microtime(true), 'method' => $request->getMethod(), 'uri' => $request->getURI(), 'ip' => $request->getClientAddress(true) ) ); foreach ($this->collectors as $name => $collector) { $this->data[$name] = $collector->collect(); } // Remove all invalid (non UTF-8) characters array_walk_recursive( $this->data, function (&$item) { if (is_string($item) && !mb_check_encoding($item, 'UTF-8')) { $item = mb_convert_encoding($item, 'UTF-8', 'UTF-8'); } } ); if ($this->storage !== null) { $this->storage->save($this->getCurrentRequestId(), $this->data); } return $this->data; }
php
public function collect() { $this->sortCollectors(); /** @var Request $request */ $request = $this->di['request']; $this->data = array( '__meta' => array( 'id' => $this->getCurrentRequestId(), 'datetime' => date('Y-m-d H:i:s'), 'utime' => microtime(true), 'method' => $request->getMethod(), 'uri' => $request->getURI(), 'ip' => $request->getClientAddress(true) ) ); foreach ($this->collectors as $name => $collector) { $this->data[$name] = $collector->collect(); } // Remove all invalid (non UTF-8) characters array_walk_recursive( $this->data, function (&$item) { if (is_string($item) && !mb_check_encoding($item, 'UTF-8')) { $item = mb_convert_encoding($item, 'UTF-8', 'UTF-8'); } } ); if ($this->storage !== null) { $this->storage->save($this->getCurrentRequestId(), $this->data); } return $this->data; }
[ "public", "function", "collect", "(", ")", "{", "$", "this", "->", "sortCollectors", "(", ")", ";", "/** @var Request $request */", "$", "request", "=", "$", "this", "->", "di", "[", "'request'", "]", ";", "$", "this", "->", "data", "=", "array", "(", ...
Collects the data from the collectors @return array
[ "Collects", "the", "data", "from", "the", "collectors" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/PhalconDebugbar.php#L745-L781
snowair/phalcon-debugbar
src/PhalconDebugbar.php
PhalconDebugbar.injectDebugbar
public function injectDebugbar(Response $response) { $content = $response->getContent(); $renderer = $this->getJavascriptRenderer(); $openHandlerUrl = $this->di['url']->getStatic( array('for'=>'debugbar.openhandler') ); $renderer->setOpenHandlerUrl($openHandlerUrl); $renderedContent = $renderer->renderHead() . $renderer->render(); $pos = strripos($content, '</body>'); if (false !== $pos) { $content = substr($content, 0, $pos) . $renderedContent . substr($content, $pos); } else { $content = $content . $renderedContent; } $response->setContent($content); }
php
public function injectDebugbar(Response $response) { $content = $response->getContent(); $renderer = $this->getJavascriptRenderer(); $openHandlerUrl = $this->di['url']->getStatic( array('for'=>'debugbar.openhandler') ); $renderer->setOpenHandlerUrl($openHandlerUrl); $renderedContent = $renderer->renderHead() . $renderer->render(); $pos = strripos($content, '</body>'); if (false !== $pos) { $content = substr($content, 0, $pos) . $renderedContent . substr($content, $pos); } else { $content = $content . $renderedContent; } $response->setContent($content); }
[ "public", "function", "injectDebugbar", "(", "Response", "$", "response", ")", "{", "$", "content", "=", "$", "response", "->", "getContent", "(", ")", ";", "$", "renderer", "=", "$", "this", "->", "getJavascriptRenderer", "(", ")", ";", "$", "openHandlerU...
Injects the web debug toolbar into the given Response. Based on https://github.com/symfony/WebProfilerBundle/blob/master/EventListener/WebDebugToolbarListener.php @param Response $response
[ "Injects", "the", "web", "debug", "toolbar", "into", "the", "given", "Response", ".", "Based", "on", "https", ":", "//", "github", ".", "com", "/", "symfony", "/", "WebProfilerBundle", "/", "blob", "/", "master", "/", "EventListener", "/", "WebDebugToolbarLi...
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/PhalconDebugbar.php#L789-L809
snowair/phalcon-debugbar
src/DataCollector/CacheCollector.php
CacheCollector.collect
function collect() { $inc_failed = count($this->_failed['inc']); $dec_failed = count($this->_failed['dec']); $n_saved = count($this->_saved); $n_inc = count($this->_increased); $n_dec = count($this->_decreased); $n_fetched = count($this->_fetched); $n_deleted = count($this->_deleted); $data = array( 'count' =>0, 'messages' =>array(), ); if ( $inc_failed+$dec_failed>0 ) { $data['messages'][] = array( 'message' => "Caches Failed: [ Inc:{$inc_failed} , Dec:{$dec_failed} ]", 'is_string'=> true, 'label' => 'Caches Summary' ); } $message = "Caches Count: [ Saved:{$n_saved} ; Gets:{$n_fetched}"; if ( $this->_nulls>0 ) { $message .= "(nulls:{$this->_nulls})"; } if ( $n_inc>0 ) { $message .= " ; Inc:{$n_inc}"; } if ( $n_dec>0 ) { $message .= " ; Dec:{$n_dec}"; } if ( $n_deleted>0 ) { $message .= " ; Deleted:{$n_deleted}"; } if ( $this->_flushed ) { $message .= " ; Has Flushed"; } $data['messages'][] = array( 'message' => $message.' ]', 'is_string'=> true, 'label' => 'Caches Summary' ); if ( !$this->_mode && $this->_messagesCollector ) { foreach ( $data['messages'] as $value ) { $this->_messagesCollector->addMessage($value['message'],$value['label'],$value['is_string']); } return array(); } $messages = array(); foreach ( $this->_saved as $key=>$value ) { $lifetime = ''; if ( $value['lifetime']!==null ) { $lifetime = "Lifetime=>"."{$value['lifetime']}"; } $content = $value['content']; if ( !is_string( $content ) ) { $content = $this->formatVars($content); $message= "Saved: [ Key=>\"$key\" $lifetime Value=> $content[0] ]"; }else{ $message= "Saved: [ Key=>\"$key\" $lifetime Value=> \"$content\" ]"; } $messages[] = array( 'message' => $message, 'is_string' => mb_strlen($message)>100?false:true, 'label' => 'Saved', 'time' =>$value['time'], ); } foreach ( $this->_fetched as $key=>$value ) { $content = $value['value']; if ( !is_string( $value ) ) { $content = $this->formatVars($content); $message= "Gets: [ Key=>\"$key\" Value=> $content[0] ]"; }else{ $message= "Gets: [ Key=>\"$key\" Value=> \"$content\" ]"; } $messages[] = array( 'message' => $message, 'is_string' => mb_strlen($message)>100?false:true, 'label' => 'Gets', 'time' => $value['time'], ); } foreach ( $this->_deleted as $value ) { $messages[] = array( 'message' => 'DeletedKey: [ '.$value['key'].' ]', 'is_string' => true, 'label' => 'Deleted', 'time' => $value['time'], ); } foreach ( $this->_increased as $value ) { $messages[] = array( 'message' => "Increased: [ Key:{$value['key']} , Step:{$value['step']} , NewValue:{$value['new_value']}] ", 'is_string' => true, 'label' => 'Increased', 'time' => $value['time'], ); } foreach ( $this->_decreased as $value ) { $messages[] = array( 'message' => "Decreased: [ Key:{$value['key']} , Step:{$value['step']} , NewValue:{$value['new_value']}] ", 'is_string' => true, 'label' => 'Decreased', 'time' => $value['time'], ); } foreach ( $this->_failed['inc'] as $value ) { $messages[] = array( 'message' => "IncFailed: [ Key:{$value['key']} , Step:{$value['step']}] ", 'is_string' => true, 'label' => 'IncFailed', 'time' => $value['time'], ); } foreach ( $this->_failed['dec'] as $value ) { $messages[] = array( 'message' => "DecFailed: [ Key:{$value['key']} , Step:{$value['step']}] ", 'is_string' => true, 'label' => 'DecFailed', 'time' => $value['time'], ); } $data['messages'] = array_merge($data['messages'], $this->sort($messages)); $data['count'] = count($messages); return $data; }
php
function collect() { $inc_failed = count($this->_failed['inc']); $dec_failed = count($this->_failed['dec']); $n_saved = count($this->_saved); $n_inc = count($this->_increased); $n_dec = count($this->_decreased); $n_fetched = count($this->_fetched); $n_deleted = count($this->_deleted); $data = array( 'count' =>0, 'messages' =>array(), ); if ( $inc_failed+$dec_failed>0 ) { $data['messages'][] = array( 'message' => "Caches Failed: [ Inc:{$inc_failed} , Dec:{$dec_failed} ]", 'is_string'=> true, 'label' => 'Caches Summary' ); } $message = "Caches Count: [ Saved:{$n_saved} ; Gets:{$n_fetched}"; if ( $this->_nulls>0 ) { $message .= "(nulls:{$this->_nulls})"; } if ( $n_inc>0 ) { $message .= " ; Inc:{$n_inc}"; } if ( $n_dec>0 ) { $message .= " ; Dec:{$n_dec}"; } if ( $n_deleted>0 ) { $message .= " ; Deleted:{$n_deleted}"; } if ( $this->_flushed ) { $message .= " ; Has Flushed"; } $data['messages'][] = array( 'message' => $message.' ]', 'is_string'=> true, 'label' => 'Caches Summary' ); if ( !$this->_mode && $this->_messagesCollector ) { foreach ( $data['messages'] as $value ) { $this->_messagesCollector->addMessage($value['message'],$value['label'],$value['is_string']); } return array(); } $messages = array(); foreach ( $this->_saved as $key=>$value ) { $lifetime = ''; if ( $value['lifetime']!==null ) { $lifetime = "Lifetime=>"."{$value['lifetime']}"; } $content = $value['content']; if ( !is_string( $content ) ) { $content = $this->formatVars($content); $message= "Saved: [ Key=>\"$key\" $lifetime Value=> $content[0] ]"; }else{ $message= "Saved: [ Key=>\"$key\" $lifetime Value=> \"$content\" ]"; } $messages[] = array( 'message' => $message, 'is_string' => mb_strlen($message)>100?false:true, 'label' => 'Saved', 'time' =>$value['time'], ); } foreach ( $this->_fetched as $key=>$value ) { $content = $value['value']; if ( !is_string( $value ) ) { $content = $this->formatVars($content); $message= "Gets: [ Key=>\"$key\" Value=> $content[0] ]"; }else{ $message= "Gets: [ Key=>\"$key\" Value=> \"$content\" ]"; } $messages[] = array( 'message' => $message, 'is_string' => mb_strlen($message)>100?false:true, 'label' => 'Gets', 'time' => $value['time'], ); } foreach ( $this->_deleted as $value ) { $messages[] = array( 'message' => 'DeletedKey: [ '.$value['key'].' ]', 'is_string' => true, 'label' => 'Deleted', 'time' => $value['time'], ); } foreach ( $this->_increased as $value ) { $messages[] = array( 'message' => "Increased: [ Key:{$value['key']} , Step:{$value['step']} , NewValue:{$value['new_value']}] ", 'is_string' => true, 'label' => 'Increased', 'time' => $value['time'], ); } foreach ( $this->_decreased as $value ) { $messages[] = array( 'message' => "Decreased: [ Key:{$value['key']} , Step:{$value['step']} , NewValue:{$value['new_value']}] ", 'is_string' => true, 'label' => 'Decreased', 'time' => $value['time'], ); } foreach ( $this->_failed['inc'] as $value ) { $messages[] = array( 'message' => "IncFailed: [ Key:{$value['key']} , Step:{$value['step']}] ", 'is_string' => true, 'label' => 'IncFailed', 'time' => $value['time'], ); } foreach ( $this->_failed['dec'] as $value ) { $messages[] = array( 'message' => "DecFailed: [ Key:{$value['key']} , Step:{$value['step']}] ", 'is_string' => true, 'label' => 'DecFailed', 'time' => $value['time'], ); } $data['messages'] = array_merge($data['messages'], $this->sort($messages)); $data['count'] = count($messages); return $data; }
[ "function", "collect", "(", ")", "{", "$", "inc_failed", "=", "count", "(", "$", "this", "->", "_failed", "[", "'inc'", "]", ")", ";", "$", "dec_failed", "=", "count", "(", "$", "this", "->", "_failed", "[", "'dec'", "]", ")", ";", "$", "n_saved", ...
Called by the DebugBar when data needs to be collected @return array Collected data
[ "Called", "by", "the", "DebugBar", "when", "data", "needs", "to", "be", "collected" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/DataCollector/CacheCollector.php#L103-L229
snowair/phalcon-debugbar
src/Storage/ElasticSearch.php
ElasticSearch.save
function save( $id, $data ) { $data['__meta']['sid'] = $this->sid; $params = [ 'index' => $this->config->index, 'type' => $this->config->type, 'id' => $id, 'body' => $data, ]; $this->client->index($params); }
php
function save( $id, $data ) { $data['__meta']['sid'] = $this->sid; $params = [ 'index' => $this->config->index, 'type' => $this->config->type, 'id' => $id, 'body' => $data, ]; $this->client->index($params); }
[ "function", "save", "(", "$", "id", ",", "$", "data", ")", "{", "$", "data", "[", "'__meta'", "]", "[", "'sid'", "]", "=", "$", "this", "->", "sid", ";", "$", "params", "=", "[", "'index'", "=>", "$", "this", "->", "config", "->", "index", ",",...
Saves collected data @param string $id @param string $data
[ "Saves", "collected", "data" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/ElasticSearch.php#L59-L71
snowair/phalcon-debugbar
src/Storage/ElasticSearch.php
ElasticSearch.get
function get( $id ) { $params = [ 'index' => $this->config->index, 'type' => $this->config->type, 'id' => $id, ]; $response = $this->client->get($params); return $response['_source']; }
php
function get( $id ) { $params = [ 'index' => $this->config->index, 'type' => $this->config->type, 'id' => $id, ]; $response = $this->client->get($params); return $response['_source']; }
[ "function", "get", "(", "$", "id", ")", "{", "$", "params", "=", "[", "'index'", "=>", "$", "this", "->", "config", "->", "index", ",", "'type'", "=>", "$", "this", "->", "config", "->", "type", ",", "'id'", "=>", "$", "id", ",", "]", ";", "$",...
Returns collected data with the specified id @param string $id @return array
[ "Returns", "collected", "data", "with", "the", "specified", "id" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/ElasticSearch.php#L80-L90
snowair/phalcon-debugbar
src/Storage/ElasticSearch.php
ElasticSearch.find
function find( array $filters = array(), $max = 20, $offset = 0 ) { $index['index'] = $this->config->index; $index['type'] = $this->config->type; $index['body']['query']['bool']['must']= [ ['match_phrase'=>[ '__meta.sid'=>$this->sid, ]] ]; if (isset($filters['method'])) { $index['body']['query']['bool']['must'][] = [ 'match_phrase' => [ '__meta.method' => $filters['method'] ]]; } if (isset($filters['uri'])) { $index['body']['query']['bool']['must'][] = [ 'match_phrase' => [ '__meta.uri' => $filters['uri'] ]]; } if (isset($filters['ip'])) { $index['body']['query']['bool']['must'][] = [ 'match_phrase' => [ '__meta.ip' => $filters['ip'] ]]; } $index['size'] = $max; $index['from'] = $offset; $response = $this->client->search($index); $result = array(); foreach ($response['hits']['hits'] as $value) { if (isset($value['_source']['__meta'])) { $result[] = $value['_source']['__meta']; } } return $result; }
php
function find( array $filters = array(), $max = 20, $offset = 0 ) { $index['index'] = $this->config->index; $index['type'] = $this->config->type; $index['body']['query']['bool']['must']= [ ['match_phrase'=>[ '__meta.sid'=>$this->sid, ]] ]; if (isset($filters['method'])) { $index['body']['query']['bool']['must'][] = [ 'match_phrase' => [ '__meta.method' => $filters['method'] ]]; } if (isset($filters['uri'])) { $index['body']['query']['bool']['must'][] = [ 'match_phrase' => [ '__meta.uri' => $filters['uri'] ]]; } if (isset($filters['ip'])) { $index['body']['query']['bool']['must'][] = [ 'match_phrase' => [ '__meta.ip' => $filters['ip'] ]]; } $index['size'] = $max; $index['from'] = $offset; $response = $this->client->search($index); $result = array(); foreach ($response['hits']['hits'] as $value) { if (isset($value['_source']['__meta'])) { $result[] = $value['_source']['__meta']; } } return $result; }
[ "function", "find", "(", "array", "$", "filters", "=", "array", "(", ")", ",", "$", "max", "=", "20", ",", "$", "offset", "=", "0", ")", "{", "$", "index", "[", "'index'", "]", "=", "$", "this", "->", "config", "->", "index", ";", "$", "index",...
Returns a metadata about collected data @param array $filters @param integer $max @param integer $offset @return array
[ "Returns", "a", "metadata", "about", "collected", "data" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/ElasticSearch.php#L101-L131
snowair/phalcon-debugbar
src/Storage/ElasticSearch.php
ElasticSearch.clear
function clear() { $index['index'] = $this->config->index; $index['type'] = $this->config->type; $index['body']['query']['bool']['must']= [ ['match_phrase'=>[ '__meta.sid'=>$this->sid, ]] ]; $this->client->deleteByQuery($index); }
php
function clear() { $index['index'] = $this->config->index; $index['type'] = $this->config->type; $index['body']['query']['bool']['must']= [ ['match_phrase'=>[ '__meta.sid'=>$this->sid, ]] ]; $this->client->deleteByQuery($index); }
[ "function", "clear", "(", ")", "{", "$", "index", "[", "'index'", "]", "=", "$", "this", "->", "config", "->", "index", ";", "$", "index", "[", "'type'", "]", "=", "$", "this", "->", "config", "->", "type", ";", "$", "index", "[", "'body'", "]", ...
Clears all the collected data
[ "Clears", "all", "the", "collected", "data" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/ElasticSearch.php#L136-L144
snowair/phalcon-debugbar
src/Debug.php
PhalconDebug.debugbar
protected static function debugbar(){ if ( !self::$debugbar ) { $di = Di::getDefault(); if ( $di->has( 'debugbar' ) ) { return self::$debugbar=$di->getShared('debugbar'); }else{ return self::$debugbar= new \Snowair\Debugbar\EmptyDebugbar(); } } return self::$debugbar; }
php
protected static function debugbar(){ if ( !self::$debugbar ) { $di = Di::getDefault(); if ( $di->has( 'debugbar' ) ) { return self::$debugbar=$di->getShared('debugbar'); }else{ return self::$debugbar= new \Snowair\Debugbar\EmptyDebugbar(); } } return self::$debugbar; }
[ "protected", "static", "function", "debugbar", "(", ")", "{", "if", "(", "!", "self", "::", "$", "debugbar", ")", "{", "$", "di", "=", "Di", "::", "getDefault", "(", ")", ";", "if", "(", "$", "di", "->", "has", "(", "'debugbar'", ")", ")", "{", ...
GET the debugbar service Instance @return \Snowair\Debugbar\PhalconDebugbar
[ "GET", "the", "debugbar", "service", "Instance" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Debug.php#L21-L31
snowair/phalcon-debugbar
src/Debug.php
PhalconDebug.addMessageIfTrue
public static function addMessageIfTrue($message,$condition,$label='INFO'){ if ( $condition===true ) { self::debugbar()->addMessage($message,$label); } }
php
public static function addMessageIfTrue($message,$condition,$label='INFO'){ if ( $condition===true ) { self::debugbar()->addMessage($message,$label); } }
[ "public", "static", "function", "addMessageIfTrue", "(", "$", "message", ",", "$", "condition", ",", "$", "label", "=", "'INFO'", ")", "{", "if", "(", "$", "condition", "===", "true", ")", "{", "self", "::", "debugbar", "(", ")", "->", "addMessage", "(...
Add a custom message to debugbar only when $condition===true @param $message @param $condition @param string $label
[ "Add", "a", "custom", "message", "to", "debugbar", "only", "when", "$condition", "===", "true" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Debug.php#L112-L116
snowair/phalcon-debugbar
src/Debug.php
PhalconDebug.addMessageIfFalse
public static function addMessageIfFalse($message,$condition,$label='INFO'){ if ( $condition===false ) { self::debugbar()->addMessage($message,$label); } }
php
public static function addMessageIfFalse($message,$condition,$label='INFO'){ if ( $condition===false ) { self::debugbar()->addMessage($message,$label); } }
[ "public", "static", "function", "addMessageIfFalse", "(", "$", "message", ",", "$", "condition", ",", "$", "label", "=", "'INFO'", ")", "{", "if", "(", "$", "condition", "===", "false", ")", "{", "self", "::", "debugbar", "(", ")", "->", "addMessage", ...
Add a custom message to debugbar only when $condition===false @param $message @param $condition @param string $label
[ "Add", "a", "custom", "message", "to", "debugbar", "only", "when", "$condition", "===", "false" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Debug.php#L124-L128
snowair/phalcon-debugbar
src/Debug.php
PhalconDebug.addMessageIfNull
public static function addMessageIfNull($message,$condition,$label='INFO'){ if ( $condition===null ) { self::debugbar()->addMessage($message,$label); } }
php
public static function addMessageIfNull($message,$condition,$label='INFO'){ if ( $condition===null ) { self::debugbar()->addMessage($message,$label); } }
[ "public", "static", "function", "addMessageIfNull", "(", "$", "message", ",", "$", "condition", ",", "$", "label", "=", "'INFO'", ")", "{", "if", "(", "$", "condition", "===", "null", ")", "{", "self", "::", "debugbar", "(", ")", "->", "addMessage", "(...
Add a custom message to debugbar only when $condition===null @param $message @param $condition @param string $label
[ "Add", "a", "custom", "message", "to", "debugbar", "only", "when", "$condition", "===", "null" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Debug.php#L136-L140
snowair/phalcon-debugbar
src/Debug.php
PhalconDebug.addMessageIfEmpty
public static function addMessageIfEmpty($message,$condition,$label='INFO'){ if ( empty($condition)===true ) { self::debugbar()->addMessage($message,$label); } }
php
public static function addMessageIfEmpty($message,$condition,$label='INFO'){ if ( empty($condition)===true ) { self::debugbar()->addMessage($message,$label); } }
[ "public", "static", "function", "addMessageIfEmpty", "(", "$", "message", ",", "$", "condition", ",", "$", "label", "=", "'INFO'", ")", "{", "if", "(", "empty", "(", "$", "condition", ")", "===", "true", ")", "{", "self", "::", "debugbar", "(", ")", ...
Add a custom message to debugbar only when empty($condition)===true @param $message @param $condition @param string $label
[ "Add", "a", "custom", "message", "to", "debugbar", "only", "when", "empty", "(", "$condition", ")", "===", "true" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Debug.php#L148-L152
snowair/phalcon-debugbar
src/Debug.php
PhalconDebug.addMessageIfNotEmpty
public static function addMessageIfNotEmpty($message,$condition,$label='INFO'){ if ( empty($condition)===false ) { self::debugbar()->addMessage($message,$label); } }
php
public static function addMessageIfNotEmpty($message,$condition,$label='INFO'){ if ( empty($condition)===false ) { self::debugbar()->addMessage($message,$label); } }
[ "public", "static", "function", "addMessageIfNotEmpty", "(", "$", "message", ",", "$", "condition", ",", "$", "label", "=", "'INFO'", ")", "{", "if", "(", "empty", "(", "$", "condition", ")", "===", "false", ")", "{", "self", "::", "debugbar", "(", ")"...
Add a custom message to debugbar only when empty($condition)===true @param $message @param $condition @param string $label
[ "Add", "a", "custom", "message", "to", "debugbar", "only", "when", "empty", "(", "$condition", ")", "===", "true" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Debug.php#L160-L164
snowair/phalcon-debugbar
src/Debug.php
PhalconDebug.addMeasure
public static function addMeasure($label,$start,$stop){ self::debugbar()->addMeasure($label,$start,$stop); }
php
public static function addMeasure($label,$start,$stop){ self::debugbar()->addMeasure($label,$start,$stop); }
[ "public", "static", "function", "addMeasure", "(", "$", "label", ",", "$", "start", ",", "$", "stop", ")", "{", "self", "::", "debugbar", "(", ")", "->", "addMeasure", "(", "$", "label", ",", "$", "start", ",", "$", "stop", ")", ";", "}" ]
Measure time between $stop and $start @param $label @param float $start microseconds timestamp @param float $stop microseconds timestamp
[ "Measure", "time", "between", "$stop", "and", "$start" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Debug.php#L172-L174
snowair/phalcon-debugbar
src/DataCollector/RouteCollector.php
RouteCollector.collect
function collect() { $dispatcher = $this->di['dispatcher']; $router = $this->di['router']; $route = $router->getMatchedRoute(); if ( !$route) { return array(); } $uri = $route->getPattern(); $paths = $route->getPaths(); $result['uri'] = $uri ?: '-'; $result['paths'] = $this->formatVar( $paths); if ( $params = $router->getParams()) { $result['params'] = $this->formatVar($params); } $result['HttpMethods'] = $route->getHttpMethods(); $result['RouteName'] = $route->getName(); $result['hostname'] = $route->getHostname(); if ( $this->di->has('app') && ($app=$this->di['app']) instanceof Micro ) { if ( ($handler=$app->getActiveHandler()) instanceof \Closure || is_string($handler) ) { $reflector = new \ReflectionFunction($handler); }elseif(is_array($handler)){ $reflector = new \ReflectionMethod($handler[0], $handler[1]); } }else{ $result['Moudle']=$router->getModuleName(); $result['Controller'] = $dispatcher->getActiveController() != null ? get_class( $controller_instance = $dispatcher->getActiveController()) : $controller_instance =""; $result['Action'] = $dispatcher->getActiveMethod(); $reflector = new \ReflectionMethod($controller_instance, $result['Action']); } if (isset($reflector)) { $start = $reflector->getStartLine()-1; $stop = $reflector->getEndLine(); $filename = substr($reflector->getFileName(),mb_strlen(realpath(dirname($_SERVER['DOCUMENT_ROOT'])))); $code = array_slice( file($reflector->getFileName()),$start, $stop-$start ); $result['file'] = $filename . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine() . " [CODE]: \n". implode("",$code); } return array_filter($result); }
php
function collect() { $dispatcher = $this->di['dispatcher']; $router = $this->di['router']; $route = $router->getMatchedRoute(); if ( !$route) { return array(); } $uri = $route->getPattern(); $paths = $route->getPaths(); $result['uri'] = $uri ?: '-'; $result['paths'] = $this->formatVar( $paths); if ( $params = $router->getParams()) { $result['params'] = $this->formatVar($params); } $result['HttpMethods'] = $route->getHttpMethods(); $result['RouteName'] = $route->getName(); $result['hostname'] = $route->getHostname(); if ( $this->di->has('app') && ($app=$this->di['app']) instanceof Micro ) { if ( ($handler=$app->getActiveHandler()) instanceof \Closure || is_string($handler) ) { $reflector = new \ReflectionFunction($handler); }elseif(is_array($handler)){ $reflector = new \ReflectionMethod($handler[0], $handler[1]); } }else{ $result['Moudle']=$router->getModuleName(); $result['Controller'] = $dispatcher->getActiveController() != null ? get_class( $controller_instance = $dispatcher->getActiveController()) : $controller_instance =""; $result['Action'] = $dispatcher->getActiveMethod(); $reflector = new \ReflectionMethod($controller_instance, $result['Action']); } if (isset($reflector)) { $start = $reflector->getStartLine()-1; $stop = $reflector->getEndLine(); $filename = substr($reflector->getFileName(),mb_strlen(realpath(dirname($_SERVER['DOCUMENT_ROOT'])))); $code = array_slice( file($reflector->getFileName()),$start, $stop-$start ); $result['file'] = $filename . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine() . " [CODE]: \n". implode("",$code); } return array_filter($result); }
[ "function", "collect", "(", ")", "{", "$", "dispatcher", "=", "$", "this", "->", "di", "[", "'dispatcher'", "]", ";", "$", "router", "=", "$", "this", "->", "di", "[", "'router'", "]", ";", "$", "route", "=", "$", "router", "->", "getMatchedRoute", ...
Called by the DebugBar when data needs to be collected @return array Collected data
[ "Called", "by", "the", "DebugBar", "when", "data", "needs", "to", "be", "collected" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/DataCollector/RouteCollector.php#L33-L73
snowair/phalcon-debugbar
src/DataCollector/LogsCollector.php
LogsCollector.collect
function collect() { foreach ( $this->_logs as &$log ) { if (!is_string($log['message'])) { $formated = $this->formatVars($log['message']); if ( $formated['exception'] ) { $log['label'] = '[ERROR]'; } $log['message'] = $formated[0]; } } return array( 'messages'=>$this->_logs, 'count'=>count($this->_logs), ); }
php
function collect() { foreach ( $this->_logs as &$log ) { if (!is_string($log['message'])) { $formated = $this->formatVars($log['message']); if ( $formated['exception'] ) { $log['label'] = '[ERROR]'; } $log['message'] = $formated[0]; } } return array( 'messages'=>$this->_logs, 'count'=>count($this->_logs), ); }
[ "function", "collect", "(", ")", "{", "foreach", "(", "$", "this", "->", "_logs", "as", "&", "$", "log", ")", "{", "if", "(", "!", "is_string", "(", "$", "log", "[", "'message'", "]", ")", ")", "{", "$", "formated", "=", "$", "this", "->", "for...
Called by the DebugBar when data needs to be collected @return array Collected data
[ "Called", "by", "the", "DebugBar", "when", "data", "needs", "to", "be", "collected" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/DataCollector/LogsCollector.php#L104-L118
snowair/phalcon-debugbar
src/DataCollector/QueryCollector.php
QueryCollector.normalizeFilename
protected function normalizeFilename($path) { if (file_exists($path)) { $path = realpath($path); } return substr($path,mb_strlen(realpath(dirname($_SERVER['DOCUMENT_ROOT'])))); }
php
protected function normalizeFilename($path) { if (file_exists($path)) { $path = realpath($path); } return substr($path,mb_strlen(realpath(dirname($_SERVER['DOCUMENT_ROOT'])))); }
[ "protected", "function", "normalizeFilename", "(", "$", "path", ")", "{", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "$", "path", "=", "realpath", "(", "$", "path", ")", ";", "}", "return", "substr", "(", "$", "path", ",", "mb_strlen"...
Shorten the path by removing the relative links and base dir @param string $path @return string
[ "Shorten", "the", "path", "by", "removing", "the", "relative", "links", "and", "base", "dir" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/DataCollector/QueryCollector.php#L117-L123
snowair/phalcon-debugbar
src/Phalcon/Db/Profiler.php
Profiler.startProfile
public function startProfile($sqlStatement, $sqlVariables = null, $sqlBindTypes = null) { $this->handleFailed(); $activeProfile = new Item(); if( !$sqlVariables ) { $sqlVariables = $this->_db->getSqlVariables(); } $activeProfile->setSqlStatement($sqlStatement); $activeProfile->setRealSQL($this->getRealSql($sqlStatement,$sqlVariables,$sqlBindTypes)); if ( is_array($sqlVariables) ) { $activeProfile->setSqlVariables($sqlVariables); } if (is_array($sqlBindTypes)) { $activeProfile->setSqlBindTypes($sqlBindTypes); } $activeProfile->setInitialTime(microtime(true)); if ( method_exists($this, "beforeStartProfile")) { $this->beforeStartProfile($activeProfile); } $this->_activeProfile = $activeProfile; $this->_stoped = false; return $this; }
php
public function startProfile($sqlStatement, $sqlVariables = null, $sqlBindTypes = null) { $this->handleFailed(); $activeProfile = new Item(); if( !$sqlVariables ) { $sqlVariables = $this->_db->getSqlVariables(); } $activeProfile->setSqlStatement($sqlStatement); $activeProfile->setRealSQL($this->getRealSql($sqlStatement,$sqlVariables,$sqlBindTypes)); if ( is_array($sqlVariables) ) { $activeProfile->setSqlVariables($sqlVariables); } if (is_array($sqlBindTypes)) { $activeProfile->setSqlBindTypes($sqlBindTypes); } $activeProfile->setInitialTime(microtime(true)); if ( method_exists($this, "beforeStartProfile")) { $this->beforeStartProfile($activeProfile); } $this->_activeProfile = $activeProfile; $this->_stoped = false; return $this; }
[ "public", "function", "startProfile", "(", "$", "sqlStatement", ",", "$", "sqlVariables", "=", "null", ",", "$", "sqlBindTypes", "=", "null", ")", "{", "$", "this", "->", "handleFailed", "(", ")", ";", "$", "activeProfile", "=", "new", "Item", "(", ")", ...
Starts the profile of a SQL sentence @param string $sqlStatement @param null|array $sqlVariables @param null|array $sqlBindTypes @return Profiler
[ "Starts", "the", "profile", "of", "a", "SQL", "sentence" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Phalcon/Db/Profiler.php#L70-L100
snowair/phalcon-debugbar
src/Phalcon/Db/Profiler.php
Profiler.stopProfile
public function stopProfile() { $finalTime = microtime(true); $activeProfile = $this->_activeProfile; $activeProfile->setFinalTime($finalTime); $initialTime = $activeProfile->getInitialTime(); $this->_totalSeconds = $this->_totalSeconds + ($finalTime - $initialTime); if ( $this->_db ) { $pdo = $this->_db->getInternalHandler(); $sql = $activeProfile->getSQLStatement(); $data = array( 'last_insert_id'=>0, 'affect_rows'=>0 ); $data['connection']=$this->getConnectionInfo(); if ( stripos( $sql, 'INSERT' )===0 ) { $data['last_insert_id'] = $pdo->lastInsertId(); } if ( stripos( $sql, 'INSERT')===0 || stripos( $sql, 'UPDATE')===0 || stripos( $sql, 'DELETE')===0) { $data['affect_rows'] = $this->_db->affectedRows(); } if ( stripos( $sql, 'SELECT')===0 && $this->_explainQuery ) { try{ $stmt = $pdo->query( 'explain '.$activeProfile->getRealSQL()); $data['explain'] = $stmt->fetchAll(\PDO::FETCH_CLASS); }catch (\Exception $e){ } } $activeProfile->setExtra($data); } $this->_allProfiles[] = $activeProfile; if (method_exists($this, "afterEndProfile")) { $this->afterEndProfile($activeProfile); } $this->_stoped = true; return $this; }
php
public function stopProfile() { $finalTime = microtime(true); $activeProfile = $this->_activeProfile; $activeProfile->setFinalTime($finalTime); $initialTime = $activeProfile->getInitialTime(); $this->_totalSeconds = $this->_totalSeconds + ($finalTime - $initialTime); if ( $this->_db ) { $pdo = $this->_db->getInternalHandler(); $sql = $activeProfile->getSQLStatement(); $data = array( 'last_insert_id'=>0, 'affect_rows'=>0 ); $data['connection']=$this->getConnectionInfo(); if ( stripos( $sql, 'INSERT' )===0 ) { $data['last_insert_id'] = $pdo->lastInsertId(); } if ( stripos( $sql, 'INSERT')===0 || stripos( $sql, 'UPDATE')===0 || stripos( $sql, 'DELETE')===0) { $data['affect_rows'] = $this->_db->affectedRows(); } if ( stripos( $sql, 'SELECT')===0 && $this->_explainQuery ) { try{ $stmt = $pdo->query( 'explain '.$activeProfile->getRealSQL()); $data['explain'] = $stmt->fetchAll(\PDO::FETCH_CLASS); }catch (\Exception $e){ } } $activeProfile->setExtra($data); } $this->_allProfiles[] = $activeProfile; if (method_exists($this, "afterEndProfile")) { $this->afterEndProfile($activeProfile); } $this->_stoped = true; return $this; }
[ "public", "function", "stopProfile", "(", ")", "{", "$", "finalTime", "=", "microtime", "(", "true", ")", ";", "$", "activeProfile", "=", "$", "this", "->", "_activeProfile", ";", "$", "activeProfile", "->", "setFinalTime", "(", "$", "finalTime", ")", ";",...
Stops the active profile @return PhalconProfiler
[ "Stops", "the", "active", "profile" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Phalcon/Db/Profiler.php#L172-L211
snowair/phalcon-debugbar
src/Storage/Filesystem.php
Filesystem.save
function save( $id, $data ) { if (!is_dir($this->dirname)) { if (mkdir($this->dirname, 0777, true)) { file_put_contents($this->dirname . '.gitignore', "*\n!.gitignore"); } else { throw new \Exception("Cannot create directory '$this->dirname'.."); } } file_put_contents($this->makeFilename($id), json_encode($data)); touch($this->dirname); // Randomly check if we should collect old files if (mt_rand(1, 100) <= $this->gc_probability) { $this->garbageCollect(); } }
php
function save( $id, $data ) { if (!is_dir($this->dirname)) { if (mkdir($this->dirname, 0777, true)) { file_put_contents($this->dirname . '.gitignore', "*\n!.gitignore"); } else { throw new \Exception("Cannot create directory '$this->dirname'.."); } } file_put_contents($this->makeFilename($id), json_encode($data)); touch($this->dirname); // Randomly check if we should collect old files if (mt_rand(1, 100) <= $this->gc_probability) { $this->garbageCollect(); } }
[ "function", "save", "(", "$", "id", ",", "$", "data", ")", "{", "if", "(", "!", "is_dir", "(", "$", "this", "->", "dirname", ")", ")", "{", "if", "(", "mkdir", "(", "$", "this", "->", "dirname", ",", "0777", ",", "true", ")", ")", "{", "file_...
Saves collected data @param string $id @param string $data @throws \Exception
[ "Saves", "collected", "data" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/Filesystem.php#L42-L58
snowair/phalcon-debugbar
src/Storage/Filesystem.php
Filesystem.garbageCollect
protected function garbageCollect() { $lifetime = $this->gc_lifetime*60*60; $Finder = new \RecursiveDirectoryIterator(dirname($this->dirname), \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS); $now = time(); /** @var \SplFileInfo $value */ foreach ( $Finder as $key => $value ) { if ( pathinfo($key,PATHINFO_EXTENSION)=='json' && ( $value->getMtime() + $lifetime < $now) ) { @unlink($value->getRealPath()); } elseif($value->isDir() && ( $value->getMtime() + $lifetime < $now) ){ $path = $value->getRealPath(); $dir = dir($path); while($f=$dir->read()){ if(!in_array($f,['.','..']) && is_file($path.'/'.$f)){ @unlink($path.'/'.$f); } } $dir->close(); @rmdir($value->getRealPath()); } } }
php
protected function garbageCollect() { $lifetime = $this->gc_lifetime*60*60; $Finder = new \RecursiveDirectoryIterator(dirname($this->dirname), \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS); $now = time(); /** @var \SplFileInfo $value */ foreach ( $Finder as $key => $value ) { if ( pathinfo($key,PATHINFO_EXTENSION)=='json' && ( $value->getMtime() + $lifetime < $now) ) { @unlink($value->getRealPath()); } elseif($value->isDir() && ( $value->getMtime() + $lifetime < $now) ){ $path = $value->getRealPath(); $dir = dir($path); while($f=$dir->read()){ if(!in_array($f,['.','..']) && is_file($path.'/'.$f)){ @unlink($path.'/'.$f); } } $dir->close(); @rmdir($value->getRealPath()); } } }
[ "protected", "function", "garbageCollect", "(", ")", "{", "$", "lifetime", "=", "$", "this", "->", "gc_lifetime", "*", "60", "*", "60", ";", "$", "Finder", "=", "new", "\\", "RecursiveDirectoryIterator", "(", "dirname", "(", "$", "this", "->", "dirname", ...
Delete files older then a certain age (gc_lifetime)
[ "Delete", "files", "older", "then", "a", "certain", "age", "(", "gc_lifetime", ")" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/Filesystem.php#L74-L98
snowair/phalcon-debugbar
src/Storage/Filesystem.php
Filesystem.find
function find( array $filters = array(), $max = 20, $offset = 0 ) { // Sort by modified time, newest first $sort = function (\SplFileInfo $a, \SplFileInfo $b) { return strcmp($b->getMTime(), $a->getMTime()); }; // Loop through .json files, filter the metadata and stop when max is found. $i = 0; $results = array(); $Finder = new \FilesystemIterator($this->dirname, \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS); $files = array(); foreach ( $Finder as $key=>$value ) { if ( pathinfo($key,PATHINFO_EXTENSION)=='json' ){ $files[]= $value; } } usort($files,$sort); foreach ($files as $file) { if ($i++ < $offset && empty($filters)) { $results[] = null; continue; } $data = json_decode( file_get_contents($file->getRealPath()), true); $meta = $data['__meta']; unset($data); if ($this->filter($meta, $filters)) { $results[] = $meta; } if (count($results) >= ($max + $offset)) { break; } } $array = array_slice($results, $offset, $max); return $array; }
php
function find( array $filters = array(), $max = 20, $offset = 0 ) { // Sort by modified time, newest first $sort = function (\SplFileInfo $a, \SplFileInfo $b) { return strcmp($b->getMTime(), $a->getMTime()); }; // Loop through .json files, filter the metadata and stop when max is found. $i = 0; $results = array(); $Finder = new \FilesystemIterator($this->dirname, \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS); $files = array(); foreach ( $Finder as $key=>$value ) { if ( pathinfo($key,PATHINFO_EXTENSION)=='json' ){ $files[]= $value; } } usort($files,$sort); foreach ($files as $file) { if ($i++ < $offset && empty($filters)) { $results[] = null; continue; } $data = json_decode( file_get_contents($file->getRealPath()), true); $meta = $data['__meta']; unset($data); if ($this->filter($meta, $filters)) { $results[] = $meta; } if (count($results) >= ($max + $offset)) { break; } } $array = array_slice($results, $offset, $max); return $array; }
[ "function", "find", "(", "array", "$", "filters", "=", "array", "(", ")", ",", "$", "max", "=", "20", ",", "$", "offset", "=", "0", ")", "{", "// Sort by modified time, newest first", "$", "sort", "=", "function", "(", "\\", "SplFileInfo", "$", "a", ",...
Returns a metadata about collected data @param array $filters @param integer $max @param integer $offset @return array
[ "Returns", "a", "metadata", "about", "collected", "data" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/Filesystem.php#L120-L161
snowair/phalcon-debugbar
src/Storage/Filesystem.php
Filesystem.clear
function clear() { $Finder = new \FilesystemIterator($this->dirname, \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS); foreach ( $Finder as $key => $value ) { if ( pathinfo($key,PATHINFO_EXTENSION)=='json' ) { unlink($value->getRealPath()); } } }
php
function clear() { $Finder = new \FilesystemIterator($this->dirname, \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS); foreach ( $Finder as $key => $value ) { if ( pathinfo($key,PATHINFO_EXTENSION)=='json' ) { unlink($value->getRealPath()); } } }
[ "function", "clear", "(", ")", "{", "$", "Finder", "=", "new", "\\", "FilesystemIterator", "(", "$", "this", "->", "dirname", ",", "\\", "FilesystemIterator", "::", "KEY_AS_FILENAME", "|", "\\", "FilesystemIterator", "::", "CURRENT_AS_FILEINFO", "|", "\\", "Fi...
Clears all the collected data
[ "Clears", "all", "the", "collected", "data" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/Filesystem.php#L183-L193
snowair/phalcon-debugbar
src/Monolog/Handler/Debugbar.php
Debugbar.write
protected function write( array $record ) { if ($this->_debugbar->hasCollector('log') && $this->_debugbar->shouldCollect('log') ) { $type = array_keys( $this->_levelMap,$record['level_name']); $this->_debugbar->getCollector('log') ->add( $record['message'], end($type), microtime(true), $record['context']); } }
php
protected function write( array $record ) { if ($this->_debugbar->hasCollector('log') && $this->_debugbar->shouldCollect('log') ) { $type = array_keys( $this->_levelMap,$record['level_name']); $this->_debugbar->getCollector('log') ->add( $record['message'], end($type), microtime(true), $record['context']); } }
[ "protected", "function", "write", "(", "array", "$", "record", ")", "{", "if", "(", "$", "this", "->", "_debugbar", "->", "hasCollector", "(", "'log'", ")", "&&", "$", "this", "->", "_debugbar", "->", "shouldCollect", "(", "'log'", ")", ")", "{", "$", ...
Writes the record down to the log of the implementing handler @param array $record @return void
[ "Writes", "the", "record", "down", "to", "the", "log", "of", "the", "implementing", "handler" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Monolog/Handler/Debugbar.php#L41-L48
snowair/phalcon-debugbar
src/Storage/MongoDB.php
MongoDB.save
function save($id, $data) { $data['_id'] = $id; $data['__meta']['sid'] = $this->sid; $this->collection->insertOne($data); }
php
function save($id, $data) { $data['_id'] = $id; $data['__meta']['sid'] = $this->sid; $this->collection->insertOne($data); }
[ "function", "save", "(", "$", "id", ",", "$", "data", ")", "{", "$", "data", "[", "'_id'", "]", "=", "$", "id", ";", "$", "data", "[", "'__meta'", "]", "[", "'sid'", "]", "=", "$", "this", "->", "sid", ";", "$", "this", "->", "collection", "-...
Saves collected data @param string $id @param array $data
[ "Saves", "collected", "data" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/MongoDB.php#L35-L40
snowair/phalcon-debugbar
src/Storage/MongoDB.php
MongoDB.find
function find(array $filters = array(), $max = 20, $offset = 0) { $criteria = [ '$and' => [ ['__meta.sid' => $this->sid], ], ]; if (isset($filters['method'])) { $criteria['$and'][]['__meta.method'] = $filters['method']; } if (isset($filters['uri'])) { $criteria['$and'][]['__meta.uri'] = $filters['uri']; } if (isset($filters['ip'])) { $criteria['$and'][]['__meta.ip'] = $filters['ip']; } $iterator = $this->collection->find( $criteria, [ 'skip' => (int)$offset, 'limit' => (int)$max, 'sort' => ['__meta.utime' => -1], ]); $array = iterator_to_array($iterator); $result = array(); foreach ($array as $value) { if (isset($value['__meta'])) { $result[] = $value['__meta']; } } return $result; }
php
function find(array $filters = array(), $max = 20, $offset = 0) { $criteria = [ '$and' => [ ['__meta.sid' => $this->sid], ], ]; if (isset($filters['method'])) { $criteria['$and'][]['__meta.method'] = $filters['method']; } if (isset($filters['uri'])) { $criteria['$and'][]['__meta.uri'] = $filters['uri']; } if (isset($filters['ip'])) { $criteria['$and'][]['__meta.ip'] = $filters['ip']; } $iterator = $this->collection->find( $criteria, [ 'skip' => (int)$offset, 'limit' => (int)$max, 'sort' => ['__meta.utime' => -1], ]); $array = iterator_to_array($iterator); $result = array(); foreach ($array as $value) { if (isset($value['__meta'])) { $result[] = $value['__meta']; } } return $result; }
[ "function", "find", "(", "array", "$", "filters", "=", "array", "(", ")", ",", "$", "max", "=", "20", ",", "$", "offset", "=", "0", ")", "{", "$", "criteria", "=", "[", "'$and'", "=>", "[", "[", "'__meta.sid'", "=>", "$", "this", "->", "sid", "...
Returns a metadata about collected data @param array $filters @param integer $max @param integer $offset @return array
[ "Returns", "a", "metadata", "about", "collected", "data" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/Storage/MongoDB.php#L63-L95
snowair/phalcon-debugbar
src/PhalconHttpDriver.php
PhalconHttpDriver.setHeaders
function setHeaders( array $headers ) { if ( $this->response!==null ) { foreach ( $headers as $key => $value ) { $this->response->setHeader( $key,$value ); } } }
php
function setHeaders( array $headers ) { if ( $this->response!==null ) { foreach ( $headers as $key => $value ) { $this->response->setHeader( $key,$value ); } } }
[ "function", "setHeaders", "(", "array", "$", "headers", ")", "{", "if", "(", "$", "this", "->", "response", "!==", "null", ")", "{", "foreach", "(", "$", "headers", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "response", "->"...
{@inheritDoc}
[ "{" ]
train
https://github.com/snowair/phalcon-debugbar/blob/80ccce21b206ab90d40bd5c33f3173831ab9ed9c/src/PhalconHttpDriver.php#L18-L24
dgrigg/Craft-Migration-Manager
src/services/Routes.php
Routes.export
public function export(array $ids, $fullExport = true) { // ignore incoming ids and grab all routes ids $routes = $this->getDbRoutes(); $items = array(); foreach ($routes as $route) { $obj = $this->exportItem($route, $fullExport = false); if ($obj) { $items[] = $obj; } } $this->addManifest('all'); return $items; }
php
public function export(array $ids, $fullExport = true) { // ignore incoming ids and grab all routes ids $routes = $this->getDbRoutes(); $items = array(); foreach ($routes as $route) { $obj = $this->exportItem($route, $fullExport = false); if ($obj) { $items[] = $obj; } } $this->addManifest('all'); return $items; }
[ "public", "function", "export", "(", "array", "$", "ids", ",", "$", "fullExport", "=", "true", ")", "{", "// ignore incoming ids and grab all routes ids", "$", "routes", "=", "$", "this", "->", "getDbRoutes", "(", ")", ";", "$", "items", "=", "array", "(", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Routes.php#L24-L42
dgrigg/Craft-Migration-Manager
src/services/Routes.php
Routes.exportItem
public function exportItem($route, $fullExport = false) { $newRoute = [ 'uriParts' => urlencode($route['uriParts']), 'uriPattern' => $route['uriPattern'], 'template' => $route['template'], 'site' => $route['siteId'] !== null ? Craft::$app->sites->getSiteById($route['siteId'])->handle : '', ]; return $newRoute; }
php
public function exportItem($route, $fullExport = false) { $newRoute = [ 'uriParts' => urlencode($route['uriParts']), 'uriPattern' => $route['uriPattern'], 'template' => $route['template'], 'site' => $route['siteId'] !== null ? Craft::$app->sites->getSiteById($route['siteId'])->handle : '', ]; return $newRoute; }
[ "public", "function", "exportItem", "(", "$", "route", ",", "$", "fullExport", "=", "false", ")", "{", "$", "newRoute", "=", "[", "'uriParts'", "=>", "urlencode", "(", "$", "route", "[", "'uriParts'", "]", ")", ",", "'uriPattern'", "=>", "$", "route", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Routes.php#L47-L57
dgrigg/Craft-Migration-Manager
src/services/Routes.php
Routes.importItem
public function importItem(Array $data) { $data['uriParts'] = urldecode($data['uriParts']); $uriParts = json_decode($data['uriParts'], true); if ($data['site'] === '') { $siteId = null; } else { $siteId = Craft::$app->sites->getSiteByHandle($data['site'])->id; } $result = Craft::$app->routes->saveRoute($uriParts, $data['template'], $siteId); return $result; }
php
public function importItem(Array $data) { $data['uriParts'] = urldecode($data['uriParts']); $uriParts = json_decode($data['uriParts'], true); if ($data['site'] === '') { $siteId = null; } else { $siteId = Craft::$app->sites->getSiteByHandle($data['site'])->id; } $result = Craft::$app->routes->saveRoute($uriParts, $data['template'], $siteId); return $result; }
[ "public", "function", "importItem", "(", "Array", "$", "data", ")", "{", "$", "data", "[", "'uriParts'", "]", "=", "urldecode", "(", "$", "data", "[", "'uriParts'", "]", ")", ";", "$", "uriParts", "=", "json_decode", "(", "$", "data", "[", "'uriParts'"...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Routes.php#L74-L88
dgrigg/Craft-Migration-Manager
src/services/Routes.php
Routes.deleteAllRoutes
private function deleteAllRoutes() { $routes = $this->getDbRoutes(); foreach ($routes as $route) { Craft::$app->routes->deleteRouteById($route['id']); } }
php
private function deleteAllRoutes() { $routes = $this->getDbRoutes(); foreach ($routes as $route) { Craft::$app->routes->deleteRouteById($route['id']); } }
[ "private", "function", "deleteAllRoutes", "(", ")", "{", "$", "routes", "=", "$", "this", "->", "getDbRoutes", "(", ")", ";", "foreach", "(", "$", "routes", "as", "$", "route", ")", "{", "Craft", "::", "$", "app", "->", "routes", "->", "deleteRouteById...
Deletes all routes
[ "Deletes", "all", "routes" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Routes.php#L93-L99
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getFieldByHandleContext
public static function getFieldByHandleContext($handle, $context) { $fields = Craft::$app->fields->getAllFields(null, $context); foreach ($fields as $field) { if ($field->handle == $handle) { return $field; } } return false; }
php
public static function getFieldByHandleContext($handle, $context) { $fields = Craft::$app->fields->getAllFields(null, $context); foreach ($fields as $field) { if ($field->handle == $handle) { return $field; } } return false; }
[ "public", "static", "function", "getFieldByHandleContext", "(", "$", "handle", ",", "$", "context", ")", "{", "$", "fields", "=", "Craft", "::", "$", "app", "->", "fields", "->", "getAllFields", "(", "null", ",", "$", "context", ")", ";", "foreach", "(",...
@param string $handle @param string|array|null $context @return bool|FieldModel
[ "@param", "string", "$handle", "@param", "string|array|null", "$context" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L26-L36
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getMatrixBlockType
public static function getMatrixBlockType($handle, $fieldId) { $blockTypes = Craft::$app->matrix->getBlockTypesByFieldId($fieldId); foreach ($blockTypes as $block) { if ($block->handle == $handle) { return $block; } } return false; }
php
public static function getMatrixBlockType($handle, $fieldId) { $blockTypes = Craft::$app->matrix->getBlockTypesByFieldId($fieldId); foreach ($blockTypes as $block) { if ($block->handle == $handle) { return $block; } } return false; }
[ "public", "static", "function", "getMatrixBlockType", "(", "$", "handle", ",", "$", "fieldId", ")", "{", "$", "blockTypes", "=", "Craft", "::", "$", "app", "->", "matrix", "->", "getBlockTypesByFieldId", "(", "$", "fieldId", ")", ";", "foreach", "(", "$", ...
@param $handle @param $fieldId @return bool|MatrixBlockTypeModel
[ "@param", "$handle", "@param", "$fieldId" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L44-L54
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getNeoBlockType
public static function getNeoBlockType($handle, $fieldId) { $neo = Craft::$app->plugins->getPlugin('neo'); $blockTypes = $neo->blockTypes->getByFieldId($fieldId); foreach ($blockTypes as $block) { if ($block->handle == $handle) { return $block; } } return false; }
php
public static function getNeoBlockType($handle, $fieldId) { $neo = Craft::$app->plugins->getPlugin('neo'); $blockTypes = $neo->blockTypes->getByFieldId($fieldId); foreach ($blockTypes as $block) { if ($block->handle == $handle) { return $block; } } return false; }
[ "public", "static", "function", "getNeoBlockType", "(", "$", "handle", ",", "$", "fieldId", ")", "{", "$", "neo", "=", "Craft", "::", "$", "app", "->", "plugins", "->", "getPlugin", "(", "'neo'", ")", ";", "$", "blockTypes", "=", "$", "neo", "->", "b...
@param $handle @param $fieldId @return bool|NeoBlockTypeModel
[ "@param", "$handle", "@param", "$fieldId" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L62-L73
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getAssetByHandle
public static function getAssetByHandle($element) { $volume = Craft::$app->volumes->getVolumeByHandle($element['source']); if ($volume) { $folderCriteria = new FolderCriteria(); $folderCriteria->name = $element['folder']; $folderCriteria->volumeId = $volume->id; $folder = Craft::$app->assets->findFolder($folderCriteria); if ($folder) { $query = Asset::find(); $query->volumeId($volume->id); $query->folderId($folder->id); $query->filename($element['filename']); $asset = $query->one(); if ($asset) { return $asset; } } } return false; }
php
public static function getAssetByHandle($element) { $volume = Craft::$app->volumes->getVolumeByHandle($element['source']); if ($volume) { $folderCriteria = new FolderCriteria(); $folderCriteria->name = $element['folder']; $folderCriteria->volumeId = $volume->id; $folder = Craft::$app->assets->findFolder($folderCriteria); if ($folder) { $query = Asset::find(); $query->volumeId($volume->id); $query->folderId($folder->id); $query->filename($element['filename']); $asset = $query->one(); if ($asset) { return $asset; } } } return false; }
[ "public", "static", "function", "getAssetByHandle", "(", "$", "element", ")", "{", "$", "volume", "=", "Craft", "::", "$", "app", "->", "volumes", "->", "getVolumeByHandle", "(", "$", "element", "[", "'source'", "]", ")", ";", "if", "(", "$", "volume", ...
@param array $element @return bool|BaseElementModel|null @throws Exception
[ "@param", "array", "$element" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L81-L106
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getCategoryByHandle
public static function getCategoryByHandle($element) { $categoryGroup = Craft::$app->categories->getGroupByHandle($element['category']); if ($categoryGroup) { $query = Category::find(); $query->groupId($categoryGroup->id); $query->slug($element['slug']); $category = $query->one(); if ($category) { return $category; } } return false; }
php
public static function getCategoryByHandle($element) { $categoryGroup = Craft::$app->categories->getGroupByHandle($element['category']); if ($categoryGroup) { $query = Category::find(); $query->groupId($categoryGroup->id); $query->slug($element['slug']); $category = $query->one(); if ($category) { return $category; } } return false; }
[ "public", "static", "function", "getCategoryByHandle", "(", "$", "element", ")", "{", "$", "categoryGroup", "=", "Craft", "::", "$", "app", "->", "categories", "->", "getGroupByHandle", "(", "$", "element", "[", "'category'", "]", ")", ";", "if", "(", "$",...
@param array $element @return bool|BaseElementModel|null @throws Exception
[ "@param", "array", "$element" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L114-L130
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getEntryByHandle
public static function getEntryByHandle($element) { $section = Craft::$app->sections->getSectionByHandle($element['section']); if ($section) { $query = Entry::find(); $query->sectionId($section->id); $query->slug($element['slug']); $entry = $query->one(); if ($entry) { return $entry; } } return false; }
php
public static function getEntryByHandle($element) { $section = Craft::$app->sections->getSectionByHandle($element['section']); if ($section) { $query = Entry::find(); $query->sectionId($section->id); $query->slug($element['slug']); $entry = $query->one(); if ($entry) { return $entry; } } return false; }
[ "public", "static", "function", "getEntryByHandle", "(", "$", "element", ")", "{", "$", "section", "=", "Craft", "::", "$", "app", "->", "sections", "->", "getSectionByHandle", "(", "$", "element", "[", "'section'", "]", ")", ";", "if", "(", "$", "sectio...
@param array $element @return bool|BaseElementModel|null @throws Exception
[ "@param", "array", "$element" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L138-L154
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getUserByHandle
public static function getUserByHandle($element) { $user = Craft::$app->users->getUserByUsernameOrEmail($element['username']); if ($user) { return $user; } return false; }
php
public static function getUserByHandle($element) { $user = Craft::$app->users->getUserByUsernameOrEmail($element['username']); if ($user) { return $user; } return false; }
[ "public", "static", "function", "getUserByHandle", "(", "$", "element", ")", "{", "$", "user", "=", "Craft", "::", "$", "app", "->", "users", "->", "getUserByUsernameOrEmail", "(", "$", "element", "[", "'username'", "]", ")", ";", "if", "(", "$", "user",...
@param array $element @return bool|UserModel|null
[ "@param", "array", "$element" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L161-L169
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getTagByHandle
public static function getTagByHandle($element) { $group = Craft::$app->tags->getTagGroupByHandle($element['group']); if ($group) { $query = Tag::find(); $query->groupId($group->id); $query->slug($element['slug']); $tag = $query->one(); if ($tag) { return $tag; } } }
php
public static function getTagByHandle($element) { $group = Craft::$app->tags->getTagGroupByHandle($element['group']); if ($group) { $query = Tag::find(); $query->groupId($group->id); $query->slug($element['slug']); $tag = $query->one(); if ($tag) { return $tag; } } }
[ "public", "static", "function", "getTagByHandle", "(", "$", "element", ")", "{", "$", "group", "=", "Craft", "::", "$", "app", "->", "tags", "->", "getTagGroupByHandle", "(", "$", "element", "[", "'group'", "]", ")", ";", "if", "(", "$", "group", ")", ...
@param array $element @return BaseElementModel|null @throws Exception
[ "@param", "array", "$element" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L177-L191
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getPermissionIds
public static function getPermissionIds($permissions) { foreach ($permissions as &$permission) { //determine if permission references element, get id if it does if (preg_match('/(:)/', $permission)) { $permissionParts = explode(":", $permission); $element = null; if (preg_match('/entries|entrydrafts/', $permissionParts[0])) { $element = Craft::$app->sections->getSectionByHandle($permissionParts[1]); } elseif (preg_match('/volume/', $permissionParts[0])) { $element = Craft::$app->volumes->getVolumeByHandle($permissionParts[1]); } elseif (preg_match('/categories/', $permissionParts[0])) { $element = Craft::$app->categories->getGroupByHandle($permissionParts[1]); } elseif (preg_match('/globalset/', $permissionParts[0])) { $element = Craft::$app->globals->getSetByHandle($permissionParts[1]); } if ($element != null) { $permission = $permissionParts[0].':'. (MigrationManagerHelper::isVersion('3.1') ? $element->uid : $element->id); } } } return $permissions; }
php
public static function getPermissionIds($permissions) { foreach ($permissions as &$permission) { //determine if permission references element, get id if it does if (preg_match('/(:)/', $permission)) { $permissionParts = explode(":", $permission); $element = null; if (preg_match('/entries|entrydrafts/', $permissionParts[0])) { $element = Craft::$app->sections->getSectionByHandle($permissionParts[1]); } elseif (preg_match('/volume/', $permissionParts[0])) { $element = Craft::$app->volumes->getVolumeByHandle($permissionParts[1]); } elseif (preg_match('/categories/', $permissionParts[0])) { $element = Craft::$app->categories->getGroupByHandle($permissionParts[1]); } elseif (preg_match('/globalset/', $permissionParts[0])) { $element = Craft::$app->globals->getSetByHandle($permissionParts[1]); } if ($element != null) { $permission = $permissionParts[0].':'. (MigrationManagerHelper::isVersion('3.1') ? $element->uid : $element->id); } } } return $permissions; }
[ "public", "static", "function", "getPermissionIds", "(", "$", "permissions", ")", "{", "foreach", "(", "$", "permissions", "as", "&", "$", "permission", ")", "{", "//determine if permission references element, get id if it does", "if", "(", "preg_match", "(", "'/(:)/'...
@param array $permissions @return array
[ "@param", "array", "$permissions" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L198-L223
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getPermissionHandles
public static function getPermissionHandles($permissions) { foreach ($permissions as &$permission) { //determine if permission references element, get handle if it does if (preg_match('/(:\w)/', $permission)) { $permissionParts = explode(":", $permission); $element = null; $hasUids = MigrationManagerHelper::isVersion('3.1'); if (preg_match('/entries|entrydrafts/', $permissionParts[0])) { $element = $hasUids ? Craft::$app->sections->getSectionByUid($permissionParts[1]) : Craft::$app->sections->getSectionById($permissionParts[1]); } elseif (preg_match('/volume/', $permissionParts[0])) { $element = $hasUids ? Craft::$app->volumes->getVolumeByUid($permissionParts[1]) : Craft::$app->volumes->getVolumeById($permissionParts[1]); } elseif (preg_match('/categories/', $permissionParts[0])) { $element = $hasUids ? Craft::$app->categories->getGroupByUid($permissionParts[1]) : Craft::$app->categories->getGroupById($permissionParts[1]); } elseif (preg_match('/globalset/', $permissionParts[0])) { $element = $hasUids ? MigrationManagerHelper::getGlobalSetByUid($permissionParts[1]) : Craft::$app->globals->getSetByid($permissionParts[1]); } if ($element != null) { $permission = $permissionParts[0].':'.$element->handle; } } } return $permissions; }
php
public static function getPermissionHandles($permissions) { foreach ($permissions as &$permission) { //determine if permission references element, get handle if it does if (preg_match('/(:\w)/', $permission)) { $permissionParts = explode(":", $permission); $element = null; $hasUids = MigrationManagerHelper::isVersion('3.1'); if (preg_match('/entries|entrydrafts/', $permissionParts[0])) { $element = $hasUids ? Craft::$app->sections->getSectionByUid($permissionParts[1]) : Craft::$app->sections->getSectionById($permissionParts[1]); } elseif (preg_match('/volume/', $permissionParts[0])) { $element = $hasUids ? Craft::$app->volumes->getVolumeByUid($permissionParts[1]) : Craft::$app->volumes->getVolumeById($permissionParts[1]); } elseif (preg_match('/categories/', $permissionParts[0])) { $element = $hasUids ? Craft::$app->categories->getGroupByUid($permissionParts[1]) : Craft::$app->categories->getGroupById($permissionParts[1]); } elseif (preg_match('/globalset/', $permissionParts[0])) { $element = $hasUids ? MigrationManagerHelper::getGlobalSetByUid($permissionParts[1]) : Craft::$app->globals->getSetByid($permissionParts[1]); } if ($element != null) { $permission = $permissionParts[0].':'.$element->handle; } } } return $permissions; }
[ "public", "static", "function", "getPermissionHandles", "(", "$", "permissions", ")", "{", "foreach", "(", "$", "permissions", "as", "&", "$", "permission", ")", "{", "//determine if permission references element, get handle if it does", "if", "(", "preg_match", "(", ...
@param array $permissions @return array
[ "@param", "array", "$permissions" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L230-L256
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.isVersion
public static function isVersion($version){ $currentVersion = Craft::$app->getVersion(); $version = explode('.', $version); $currentVersion = explode('.', $currentVersion); $isVersion = true; foreach($version as $key => $value){ if ((int)$currentVersion[$key] < $version[$key]){ $isVersion = false; } } return $isVersion; }
php
public static function isVersion($version){ $currentVersion = Craft::$app->getVersion(); $version = explode('.', $version); $currentVersion = explode('.', $currentVersion); $isVersion = true; foreach($version as $key => $value){ if ((int)$currentVersion[$key] < $version[$key]){ $isVersion = false; } } return $isVersion; }
[ "public", "static", "function", "isVersion", "(", "$", "version", ")", "{", "$", "currentVersion", "=", "Craft", "::", "$", "app", "->", "getVersion", "(", ")", ";", "$", "version", "=", "explode", "(", "'.'", ",", "$", "version", ")", ";", "$", "cur...
check to see if current version is greater than or equal to a version
[ "check", "to", "see", "if", "current", "version", "is", "greater", "than", "or", "equal", "to", "a", "version" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L261-L272
dgrigg/Craft-Migration-Manager
src/helpers/MigrationManagerHelper.php
MigrationManagerHelper.getTagGroupByUid
public static function getTagGroupByUid(string $uid): TagGroup { $query = TagGroup::find(); $query->andWhere(['uid' => $uid]); return $query->one() ?? new TagGroup(); }
php
public static function getTagGroupByUid(string $uid): TagGroup { $query = TagGroup::find(); $query->andWhere(['uid' => $uid]); return $query->one() ?? new TagGroup(); }
[ "public", "static", "function", "getTagGroupByUid", "(", "string", "$", "uid", ")", ":", "TagGroup", "{", "$", "query", "=", "TagGroup", "::", "find", "(", ")", ";", "$", "query", "->", "andWhere", "(", "[", "'uid'", "=>", "$", "uid", "]", ")", ";", ...
Get a tag record by uid
[ "Get", "a", "tag", "record", "by", "uid" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/helpers/MigrationManagerHelper.php#L278-L283
dgrigg/Craft-Migration-Manager
src/services/Migrations.php
Migrations.createSettingMigration
public function createSettingMigration($data) { $manifest = []; $migration = array( 'settings' => array( 'dependencies' => array(), 'elements' => array(), ), ); $empty = true; //build a list of dependencies first to avoid potential cases where items are requested by fields before being created //export them without additional fields to prevent conflicts with missing fields, field tabs can be added on the second pass //after all the fields have been created $plugin = MigrationManager::getInstance(); foreach ($this->_settingsDependencyTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getSource(), $data)) { $migration['settings']['dependencies'][$service->getDestination()] = $service->export($data[$service->getSource()], false); $empty = false; if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error, __METHOD__); } return false; } } } foreach ($this->_settingsMigrationTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getSource(), $data)) { $migration['settings']['elements'][$service->getDestination()] = $service->export($data[$service->getSource()], true); $empty = false; if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error, __METHOD__); } return false; } $manifest = array_merge($manifest, [$key => $service->getManifest()]); } } if ($empty) { $migration = null; } if (array_key_exists('migrationName', $data)){ $migrationName = trim($data['migrationName']); $migrationName = str_replace(' ', '_', $migrationName); } else { $migrationName = ''; } $this->createMigration($migration, $manifest, $migrationName); return true; }
php
public function createSettingMigration($data) { $manifest = []; $migration = array( 'settings' => array( 'dependencies' => array(), 'elements' => array(), ), ); $empty = true; //build a list of dependencies first to avoid potential cases where items are requested by fields before being created //export them without additional fields to prevent conflicts with missing fields, field tabs can be added on the second pass //after all the fields have been created $plugin = MigrationManager::getInstance(); foreach ($this->_settingsDependencyTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getSource(), $data)) { $migration['settings']['dependencies'][$service->getDestination()] = $service->export($data[$service->getSource()], false); $empty = false; if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error, __METHOD__); } return false; } } } foreach ($this->_settingsMigrationTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getSource(), $data)) { $migration['settings']['elements'][$service->getDestination()] = $service->export($data[$service->getSource()], true); $empty = false; if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error, __METHOD__); } return false; } $manifest = array_merge($manifest, [$key => $service->getManifest()]); } } if ($empty) { $migration = null; } if (array_key_exists('migrationName', $data)){ $migrationName = trim($data['migrationName']); $migrationName = str_replace(' ', '_', $migrationName); } else { $migrationName = ''; } $this->createMigration($migration, $manifest, $migrationName); return true; }
[ "public", "function", "createSettingMigration", "(", "$", "data", ")", "{", "$", "manifest", "=", "[", "]", ";", "$", "migration", "=", "array", "(", "'settings'", "=>", "array", "(", "'dependencies'", "=>", "array", "(", ")", ",", "'elements'", "=>", "a...
create a new migration file based on input element types @param $data @return bool
[ "create", "a", "new", "migration", "file", "based", "on", "input", "element", "types" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Migrations.php#L56-L124
dgrigg/Craft-Migration-Manager
src/services/Migrations.php
Migrations.createContentMigration
public function createContentMigration($data) { $manifest = []; $migration = array( 'content' => array(), ); $empty = true; $plugin = MigrationManager::getInstance(); foreach ($this->_contentMigrationTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getSource(), $data)) { $migration['content'][$service->getDestination()] = $service->export($data[$service->getSource()], true); $empty = false; if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error); } return false; } $manifest = array_merge($manifest, [$key => $service->getManifest()]); } } if ($empty) { $migration = null; } $this->createMigration($migration, $manifest); return true; }
php
public function createContentMigration($data) { $manifest = []; $migration = array( 'content' => array(), ); $empty = true; $plugin = MigrationManager::getInstance(); foreach ($this->_contentMigrationTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getSource(), $data)) { $migration['content'][$service->getDestination()] = $service->export($data[$service->getSource()], true); $empty = false; if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error); } return false; } $manifest = array_merge($manifest, [$key => $service->getManifest()]); } } if ($empty) { $migration = null; } $this->createMigration($migration, $manifest); return true; }
[ "public", "function", "createContentMigration", "(", "$", "data", ")", "{", "$", "manifest", "=", "[", "]", ";", "$", "migration", "=", "array", "(", "'content'", "=>", "array", "(", ")", ",", ")", ";", "$", "empty", "=", "true", ";", "$", "plugin", ...
create a new migration file based on selected content elements @param $data @return bool
[ "create", "a", "new", "migration", "file", "based", "on", "selected", "content", "elements" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Migrations.php#L133-L170
dgrigg/Craft-Migration-Manager
src/services/Migrations.php
Migrations.createMigration
private function createMigration($migration, $manifest = array(), $migrationName = '') { $empty = is_null($migration); $date = new DateTime(); $name = 'm%s_migration'; $description = []; if ($migrationName == '') { foreach ($manifest as $key => $value) { $description[] = $key; foreach ($value as $item) { $description[] = $item; } } } else { $description[] = $migrationName; } if (!$empty || count($description)>0) { $description = implode('_', $description); $name .= '_' . MigrationManagerHelper::slugify($description); } $filename = sprintf($name, $date->format('ymd_His')); $filename = substr($filename, 0, 250); $filename = str_replace('-', '_', $filename); $migrator = Craft::$app->getContentMigrator(); $migrationPath = $migrator->migrationPath; $path = sprintf($migrationPath . '/%s.php', $filename); $pathLen = strlen($path); if ($pathLen > 255) { $migrationPathLen = strlen($migrationPath); $filename = substr($filename, 0, 250 - $migrationPathLen); $path = sprintf($migrationPath . '/%s.php', $filename); } $migration = json_encode($migration, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //escape backslashes //$migration = str_replace('\\', '\\\\', $migration); $content = Craft::$app->view->renderTemplate('migrationmanager/_migration', array('empty' => $empty, 'migration' => $migration, 'className' => $filename, 'manifest' => $manifest, true)); FileHelper::writeToFile($path, $content); // mark the migration as completed if it's not a blank one if (!$empty) { $migrator->addMigrationHistory($filename); } }
php
private function createMigration($migration, $manifest = array(), $migrationName = '') { $empty = is_null($migration); $date = new DateTime(); $name = 'm%s_migration'; $description = []; if ($migrationName == '') { foreach ($manifest as $key => $value) { $description[] = $key; foreach ($value as $item) { $description[] = $item; } } } else { $description[] = $migrationName; } if (!$empty || count($description)>0) { $description = implode('_', $description); $name .= '_' . MigrationManagerHelper::slugify($description); } $filename = sprintf($name, $date->format('ymd_His')); $filename = substr($filename, 0, 250); $filename = str_replace('-', '_', $filename); $migrator = Craft::$app->getContentMigrator(); $migrationPath = $migrator->migrationPath; $path = sprintf($migrationPath . '/%s.php', $filename); $pathLen = strlen($path); if ($pathLen > 255) { $migrationPathLen = strlen($migrationPath); $filename = substr($filename, 0, 250 - $migrationPathLen); $path = sprintf($migrationPath . '/%s.php', $filename); } $migration = json_encode($migration, JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //escape backslashes //$migration = str_replace('\\', '\\\\', $migration); $content = Craft::$app->view->renderTemplate('migrationmanager/_migration', array('empty' => $empty, 'migration' => $migration, 'className' => $filename, 'manifest' => $manifest, true)); FileHelper::writeToFile($path, $content); // mark the migration as completed if it's not a blank one if (!$empty) { $migrator->addMigrationHistory($filename); } }
[ "private", "function", "createMigration", "(", "$", "migration", ",", "$", "manifest", "=", "array", "(", ")", ",", "$", "migrationName", "=", "''", ")", "{", "$", "empty", "=", "is_null", "(", "$", "migration", ")", ";", "$", "date", "=", "new", "Da...
@param mixed $migration data to write in migration file @param array $manifest @throws Exception
[ "@param", "mixed", "$migration", "data", "to", "write", "in", "migration", "file", "@param", "array", "$manifest" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Migrations.php#L178-L230
dgrigg/Craft-Migration-Manager
src/services/Migrations.php
Migrations.import
public function import($data) { $data = iconv('UTF-8', 'UTF-8//IGNORE', StringHelper::convertToUtf8($data)); $data = json_decode($data, true); if (json_last_error() != JSON_ERROR_NONE){ Craft::error('Migration Manager JSON error', __METHOD__); Craft::error(json_last_error(), __METHOD__); Craft::error(json_last_error_msg(), __METHOD__); } $plugin = MigrationManager::getInstance(); if (array_key_exists('settings', $data)) { // run through dependencies first to create any elements that need to be in place for fields, field layouts and other dependencies foreach ($this->_settingsDependencyTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getDestination(), $data['settings']['dependencies'])) { $service->import($data['settings']['dependencies'][$service->getDestination()]); if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error , __METHOD__); } return false; } } } foreach ($this->_settingsMigrationTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getDestination(), $data['settings']['elements'])) { $service->import($data['settings']['elements'][$service->getDestination()]); if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error, __METHOD__); } return false; } } } } if (array_key_exists('content', $data)) { foreach ($this->_contentMigrationTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getDestination(), $data['content'])) { $service->import($data['content'][$service->getDestination()]); if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error, __METHOD__); } return false; } } } } return true; }
php
public function import($data) { $data = iconv('UTF-8', 'UTF-8//IGNORE', StringHelper::convertToUtf8($data)); $data = json_decode($data, true); if (json_last_error() != JSON_ERROR_NONE){ Craft::error('Migration Manager JSON error', __METHOD__); Craft::error(json_last_error(), __METHOD__); Craft::error(json_last_error_msg(), __METHOD__); } $plugin = MigrationManager::getInstance(); if (array_key_exists('settings', $data)) { // run through dependencies first to create any elements that need to be in place for fields, field layouts and other dependencies foreach ($this->_settingsDependencyTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getDestination(), $data['settings']['dependencies'])) { $service->import($data['settings']['dependencies'][$service->getDestination()]); if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error , __METHOD__); } return false; } } } foreach ($this->_settingsMigrationTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getDestination(), $data['settings']['elements'])) { $service->import($data['settings']['elements'][$service->getDestination()]); if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error, __METHOD__); } return false; } } } } if (array_key_exists('content', $data)) { foreach ($this->_contentMigrationTypes as $key => $value) { $service = $plugin->get($value); if (array_key_exists($service->getDestination(), $data['content'])) { $service->import($data['content'][$service->getDestination()]); if ($service->hasErrors()) { $errors = $service->getErrors(); foreach ($errors as $error) { Craft::error($error, __METHOD__); } return false; } } } } return true; }
[ "public", "function", "import", "(", "$", "data", ")", "{", "$", "data", "=", "iconv", "(", "'UTF-8'", ",", "'UTF-8//IGNORE'", ",", "StringHelper", "::", "convertToUtf8", "(", "$", "data", ")", ")", ";", "$", "data", "=", "json_decode", "(", "$", "data...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Migrations.php#L235-L296
dgrigg/Craft-Migration-Manager
src/services/Migrations.php
Migrations.runMigrations
public function runMigrations($migrationNames = []) { // This might take a while App::maxPowerCaptain(); if (empty($migrationNames)) { $migrationNames = $this->getNewMigrations(); } $total = count($migrationNames); $n = count($migrationNames); if ($n === $total) { $logMessage = "Total $n new ".($n === 1 ? 'migration' : 'migrations').' to be applied:'; } else { $logMessage = "Total $n out of $total new ".($total === 1 ? 'migration' : 'migrations').' to be applied:'; } foreach ($migrationNames as $migrationName) { $logMessage .= "\n\t$migrationName"; } foreach ($migrationNames as $migrationName) { try { $migrator = Craft::$app->getContentMigrator(); $migrator->migrateUp($migrationName); } catch (MigrationException $e) { Craft::error('Migration failed. The rest of the migrations are cancelled.', __METHOD__); //throw $e; return false; } } return true; }
php
public function runMigrations($migrationNames = []) { // This might take a while App::maxPowerCaptain(); if (empty($migrationNames)) { $migrationNames = $this->getNewMigrations(); } $total = count($migrationNames); $n = count($migrationNames); if ($n === $total) { $logMessage = "Total $n new ".($n === 1 ? 'migration' : 'migrations').' to be applied:'; } else { $logMessage = "Total $n out of $total new ".($total === 1 ? 'migration' : 'migrations').' to be applied:'; } foreach ($migrationNames as $migrationName) { $logMessage .= "\n\t$migrationName"; } foreach ($migrationNames as $migrationName) { try { $migrator = Craft::$app->getContentMigrator(); $migrator->migrateUp($migrationName); } catch (MigrationException $e) { Craft::error('Migration failed. The rest of the migrations are cancelled.', __METHOD__); //throw $e; return false; } } return true; }
[ "public", "function", "runMigrations", "(", "$", "migrationNames", "=", "[", "]", ")", "{", "// This might take a while", "App", "::", "maxPowerCaptain", "(", ")", ";", "if", "(", "empty", "(", "$", "migrationNames", ")", ")", "{", "$", "migrationNames", "="...
@param array $migrationsToRun @return bool @throws \CDbException
[ "@param", "array", "$migrationsToRun" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Migrations.php#L304-L338
dgrigg/Craft-Migration-Manager
src/services/Sections.php
Sections.exportItem
public function exportItem($id, $fullExport = false) { $section = Craft::$app->sections->getSectionById($id); if (!$section) { return false; } $newSection = [ 'name' => $section->attributes['name'], 'handle' => $section->attributes['handle'], 'type' => $section->attributes['type'], 'enableVersioning' => $section->attributes['enableVersioning'], 'propagateEntries' => $section->attributes['propagateEntries'], ]; if ($section->type == Section::TYPE_STRUCTURE){ $newSection['maxLevels'] = $section->attributes['maxLevels']; } $this->addManifest($section->attributes['handle']); $siteSettings = $section->getSiteSettings(); $newSection['sites'] = array(); foreach ($siteSettings as $siteSetting) { $site = Craft::$app->sites->getSiteById($siteSetting->siteId); $newSection['sites'][$site->handle] = [ 'site' => $site->handle, 'hasUrls' => $siteSetting->hasUrls, 'uriFormat' => $siteSetting->uriFormat, 'enabledByDefault' => $siteSetting->enabledByDefault, 'template' => $siteSetting->template, ]; } $newSection['entrytypes'] = array(); $sectionEntryTypes = $section->getEntryTypes(); foreach ($sectionEntryTypes as $entryType) { $newEntryType = [ 'sectionHandle' => $section->attributes['handle'], 'hasTitleField' => $entryType->attributes['hasTitleField'], 'titleLabel' => $entryType->attributes['titleLabel'], 'titleFormat' => $entryType->attributes['titleFormat'], 'name' => $entryType->attributes['name'], 'handle' => $entryType->attributes['handle'], 'fieldLayout' => array(), 'requiredFields' => array(), ]; if ($newEntryType['titleFormat'] === null) { unset($newEntryType['titleFormat']); } $fieldLayout = $entryType->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { $newEntryType['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newEntryType['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newEntryType['requiredFields'][] = $tabField->handle; } } } array_push($newSection['entrytypes'], $newEntryType); } if ($fullExport) { $newSection = $this->onBeforeExport($section, $newSection); } return $newSection; }
php
public function exportItem($id, $fullExport = false) { $section = Craft::$app->sections->getSectionById($id); if (!$section) { return false; } $newSection = [ 'name' => $section->attributes['name'], 'handle' => $section->attributes['handle'], 'type' => $section->attributes['type'], 'enableVersioning' => $section->attributes['enableVersioning'], 'propagateEntries' => $section->attributes['propagateEntries'], ]; if ($section->type == Section::TYPE_STRUCTURE){ $newSection['maxLevels'] = $section->attributes['maxLevels']; } $this->addManifest($section->attributes['handle']); $siteSettings = $section->getSiteSettings(); $newSection['sites'] = array(); foreach ($siteSettings as $siteSetting) { $site = Craft::$app->sites->getSiteById($siteSetting->siteId); $newSection['sites'][$site->handle] = [ 'site' => $site->handle, 'hasUrls' => $siteSetting->hasUrls, 'uriFormat' => $siteSetting->uriFormat, 'enabledByDefault' => $siteSetting->enabledByDefault, 'template' => $siteSetting->template, ]; } $newSection['entrytypes'] = array(); $sectionEntryTypes = $section->getEntryTypes(); foreach ($sectionEntryTypes as $entryType) { $newEntryType = [ 'sectionHandle' => $section->attributes['handle'], 'hasTitleField' => $entryType->attributes['hasTitleField'], 'titleLabel' => $entryType->attributes['titleLabel'], 'titleFormat' => $entryType->attributes['titleFormat'], 'name' => $entryType->attributes['name'], 'handle' => $entryType->attributes['handle'], 'fieldLayout' => array(), 'requiredFields' => array(), ]; if ($newEntryType['titleFormat'] === null) { unset($newEntryType['titleFormat']); } $fieldLayout = $entryType->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { $newEntryType['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newEntryType['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newEntryType['requiredFields'][] = $tabField->handle; } } } array_push($newSection['entrytypes'], $newEntryType); } if ($fullExport) { $newSection = $this->onBeforeExport($section, $newSection); } return $newSection; }
[ "public", "function", "exportItem", "(", "$", "id", ",", "$", "fullExport", "=", "false", ")", "{", "$", "section", "=", "Craft", "::", "$", "app", "->", "sections", "->", "getSectionById", "(", "$", "id", ")", ";", "if", "(", "!", "$", "section", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Sections.php#L29-L108
dgrigg/Craft-Migration-Manager
src/services/Sections.php
Sections.importItem
public function importItem(array $data) { $result = true; $existing = Craft::$app->sections->getSectionByHandle($data['handle']); if ($existing) { $this->mergeUpdates($data, $existing); } $section = $this->createModel($data); if ($section !== false){ $event = $this->onBeforeImport($section, $data); if ($event->isValid) { if (Craft::$app->sections->saveSection($event->element)) { $this->onAfterImport($event->element, $data); //only need for sections pre project config if (!MigrationManagerHelper::isVersion('3.1') && !$existing) { //wipe out the default entry type $defaultEntryType = Craft::$app->sections->getEntryTypesBySectionId($section->id); if ($defaultEntryType) { Craft::$app->sections->deleteEntryTypeById($defaultEntryType[0]->id); } } //add entry types foreach ($data['entrytypes'] as $key => $newEntryType) { $existingType = $this->getSectionEntryTypeByHandle($newEntryType['handle'], $section->id); if ($existingType) { $this->mergeEntryType($newEntryType, $existingType); } $entryType = $this->createEntryType($newEntryType, $section); if (!Craft::$app->sections->saveEntryType($entryType)) { $result = false; } } } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' section.'); $result = false; } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' section.'); $this->addError('error', $event->error); return false; } } else { return false; } return $result; }
php
public function importItem(array $data) { $result = true; $existing = Craft::$app->sections->getSectionByHandle($data['handle']); if ($existing) { $this->mergeUpdates($data, $existing); } $section = $this->createModel($data); if ($section !== false){ $event = $this->onBeforeImport($section, $data); if ($event->isValid) { if (Craft::$app->sections->saveSection($event->element)) { $this->onAfterImport($event->element, $data); //only need for sections pre project config if (!MigrationManagerHelper::isVersion('3.1') && !$existing) { //wipe out the default entry type $defaultEntryType = Craft::$app->sections->getEntryTypesBySectionId($section->id); if ($defaultEntryType) { Craft::$app->sections->deleteEntryTypeById($defaultEntryType[0]->id); } } //add entry types foreach ($data['entrytypes'] as $key => $newEntryType) { $existingType = $this->getSectionEntryTypeByHandle($newEntryType['handle'], $section->id); if ($existingType) { $this->mergeEntryType($newEntryType, $existingType); } $entryType = $this->createEntryType($newEntryType, $section); if (!Craft::$app->sections->saveEntryType($entryType)) { $result = false; } } } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' section.'); $result = false; } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' section.'); $this->addError('error', $event->error); return false; } } else { return false; } return $result; }
[ "public", "function", "importItem", "(", "array", "$", "data", ")", "{", "$", "result", "=", "true", ";", "$", "existing", "=", "Craft", "::", "$", "app", "->", "sections", "->", "getSectionByHandle", "(", "$", "data", "[", "'handle'", "]", ")", ";", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Sections.php#L113-L167
dgrigg/Craft-Migration-Manager
src/services/Sections.php
Sections.createModel
public function createModel(array $data) { $section = new Section(); if (array_key_exists('id', $data)) { $section->id = $data['id']; } $section->name = $data['name']; $section->handle = $data['handle']; $section->type = $data['type']; $section->enableVersioning = $data['enableVersioning']; $section->propagateEntries = $data['propagateEntries']; if ($section->type == Section::TYPE_STRUCTURE){ $section->maxLevels = $data['maxLevels']; } $allSiteSettings = []; if (array_key_exists('sites', $data)) { foreach ($data['sites'] as $key => $siteData) { //determine if locale exists $site = Craft::$app->getSites()->getSiteByHandle($key); if ($site){ $siteSettings = new Section_SiteSettings(); $siteSettings->siteId = $site->id; $siteSettings->hasUrls = $siteData['hasUrls']; $siteSettings->uriFormat = $siteData['uriFormat']; $siteSettings->template = $siteData['template']; $siteSettings->enabledByDefault = (bool)$siteData['enabledByDefault']; $allSiteSettings[$site->id] = $siteSettings; } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' section, site ' . $key . ' is not defined.'); return false; } } } $section->setSiteSettings($allSiteSettings); return $section; }
php
public function createModel(array $data) { $section = new Section(); if (array_key_exists('id', $data)) { $section->id = $data['id']; } $section->name = $data['name']; $section->handle = $data['handle']; $section->type = $data['type']; $section->enableVersioning = $data['enableVersioning']; $section->propagateEntries = $data['propagateEntries']; if ($section->type == Section::TYPE_STRUCTURE){ $section->maxLevels = $data['maxLevels']; } $allSiteSettings = []; if (array_key_exists('sites', $data)) { foreach ($data['sites'] as $key => $siteData) { //determine if locale exists $site = Craft::$app->getSites()->getSiteByHandle($key); if ($site){ $siteSettings = new Section_SiteSettings(); $siteSettings->siteId = $site->id; $siteSettings->hasUrls = $siteData['hasUrls']; $siteSettings->uriFormat = $siteData['uriFormat']; $siteSettings->template = $siteData['template']; $siteSettings->enabledByDefault = (bool)$siteData['enabledByDefault']; $allSiteSettings[$site->id] = $siteSettings; } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' section, site ' . $key . ' is not defined.'); return false; } } } $section->setSiteSettings($allSiteSettings); return $section; }
[ "public", "function", "createModel", "(", "array", "$", "data", ")", "{", "$", "section", "=", "new", "Section", "(", ")", ";", "if", "(", "array_key_exists", "(", "'id'", ",", "$", "data", ")", ")", "{", "$", "section", "->", "id", "=", "$", "data...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Sections.php#L172-L214
dgrigg/Craft-Migration-Manager
src/services/Sections.php
Sections.createEntryType
private function createEntryType($data, $section) { $entryType = new EntryType(array( 'sectionId' => $section->id, 'name' => $data['name'], 'handle' => $data['handle'], 'hasTitleField' => $data['hasTitleField'], 'titleLabel' => $data['titleLabel'], )); if (array_key_exists('titleFormat', $data)) { $entryType->titleFormat = $data['titleFormat']; } if (array_key_exists('id', $data)) { $entryType->id = $data['id']; } $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = Entry::class; $entryType->fieldLayout = $fieldLayout; return $entryType; }
php
private function createEntryType($data, $section) { $entryType = new EntryType(array( 'sectionId' => $section->id, 'name' => $data['name'], 'handle' => $data['handle'], 'hasTitleField' => $data['hasTitleField'], 'titleLabel' => $data['titleLabel'], )); if (array_key_exists('titleFormat', $data)) { $entryType->titleFormat = $data['titleFormat']; } if (array_key_exists('id', $data)) { $entryType->id = $data['id']; } $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = Entry::class; $entryType->fieldLayout = $fieldLayout; return $entryType; }
[ "private", "function", "createEntryType", "(", "$", "data", ",", "$", "section", ")", "{", "$", "entryType", "=", "new", "EntryType", "(", "array", "(", "'sectionId'", "=>", "$", "section", "->", "id", ",", "'name'", "=>", "$", "data", "[", "'name'", "...
@param array $data @param SectionModel $section @return EntryTypeModel
[ "@param", "array", "$data", "@param", "SectionModel", "$section" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Sections.php#L222-L267
dgrigg/Craft-Migration-Manager
src/services/BaseMigration.php
BaseMigration.import
public function import(array $data) { $this->clearErrors(); $result = true; foreach ($data as $section) { if ($this->importItem($section) === false) { $result = false; } } return $result; }
php
public function import(array $data) { $this->clearErrors(); $result = true; foreach ($data as $section) { if ($this->importItem($section) === false) { $result = false; } } return $result; }
[ "public", "function", "import", "(", "array", "$", "data", ")", "{", "$", "this", "->", "clearErrors", "(", ")", ";", "$", "result", "=", "true", ";", "foreach", "(", "$", "data", "as", "$", "section", ")", "{", "if", "(", "$", "this", "->", "imp...
@param array $data of data to import @return bool
[ "@param", "array", "$data", "of", "data", "to", "import" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/BaseMigration.php#L141-L153
dgrigg/Craft-Migration-Manager
src/services/BaseMigration.php
BaseMigration.onBeforeExport
public function onBeforeExport($element , array $newElement) { $event = new ExportEvent(array( 'element' => $element, 'value' => $newElement )); $this->trigger($this::EVENT_BEFORE_EXPORT_ELEMENT, $event); return $event->value; }
php
public function onBeforeExport($element , array $newElement) { $event = new ExportEvent(array( 'element' => $element, 'value' => $newElement )); $this->trigger($this::EVENT_BEFORE_EXPORT_ELEMENT, $event); return $event->value; }
[ "public", "function", "onBeforeExport", "(", "$", "element", ",", "array", "$", "newElement", ")", "{", "$", "event", "=", "new", "ExportEvent", "(", "array", "(", "'element'", "=>", "$", "element", ",", "'value'", "=>", "$", "newElement", ")", ")", ";",...
Fires an 'onBeforeExport' event. @param Event $event $event->params['element'] - element being exported via migration $event->params['value'] - current element value, change this value in the event handler to migrate a different value @return null
[ "Fires", "an", "onBeforeExport", "event", "." ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/BaseMigration.php#L179-L187
dgrigg/Craft-Migration-Manager
src/services/BaseMigration.php
BaseMigration.onBeforeImport
public function onBeforeImport($element, array $data) { $event = new ImportEvent(array( 'element' => $element, 'value' => $data )); $this->trigger($this::EVENT_BEFORE_IMPORT_ELEMENT, $event); return $event; }
php
public function onBeforeImport($element, array $data) { $event = new ImportEvent(array( 'element' => $element, 'value' => $data )); $this->trigger($this::EVENT_BEFORE_IMPORT_ELEMENT, $event); return $event; }
[ "public", "function", "onBeforeImport", "(", "$", "element", ",", "array", "$", "data", ")", "{", "$", "event", "=", "new", "ImportEvent", "(", "array", "(", "'element'", "=>", "$", "element", ",", "'value'", "=>", "$", "data", ")", ")", ";", "$", "t...
Fires an 'onBeforeImport' event. @param Event $event $event->params['element'] - model to be imported, manipulate this to change the model before it is saved $event->params['value'] - data used to create the element model @return null
[ "Fires", "an", "onBeforeImport", "event", "." ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/BaseMigration.php#L198-L207
dgrigg/Craft-Migration-Manager
src/services/BaseMigration.php
BaseMigration.onAfterImport
public function onAfterImport($element, array $data) { $event = new ImportEvent(array( 'element' => $element, 'value' => $data )); $this->trigger($this::EVENT_AFTER_IMPORT_ELEMENT, $event); }
php
public function onAfterImport($element, array $data) { $event = new ImportEvent(array( 'element' => $element, 'value' => $data )); $this->trigger($this::EVENT_AFTER_IMPORT_ELEMENT, $event); }
[ "public", "function", "onAfterImport", "(", "$", "element", ",", "array", "$", "data", ")", "{", "$", "event", "=", "new", "ImportEvent", "(", "array", "(", "'element'", "=>", "$", "element", ",", "'value'", "=>", "$", "data", ")", ")", ";", "$", "th...
Fires an 'onAfterImport' event. @param Event $event $event->params['element'] - model that was imported $event->params['value'] - data used to create the element model @return null
[ "Fires", "an", "onAfterImport", "event", "." ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/BaseMigration.php#L218-L226
dgrigg/Craft-Migration-Manager
src/services/Sites.php
Sites.exportItem
public function exportItem($id, $fullExport = false) { $site = Craft::$app->sites->getSiteById($id); $newSite = [ 'name' => $site->name, 'handle' => $site->handle, 'group' => $site->group->name, 'language' => $site->language, 'hasUrls' => $site->hasUrls, 'baseUrl' => $site->baseUrl, 'primary' => $site->primary, 'sortOrder' => $site->sortOrder ]; $this->addManifest($site->handle); if ($fullExport) { $newSite = $this->onBeforeExport($site, $newSite); } return $newSite; }
php
public function exportItem($id, $fullExport = false) { $site = Craft::$app->sites->getSiteById($id); $newSite = [ 'name' => $site->name, 'handle' => $site->handle, 'group' => $site->group->name, 'language' => $site->language, 'hasUrls' => $site->hasUrls, 'baseUrl' => $site->baseUrl, 'primary' => $site->primary, 'sortOrder' => $site->sortOrder ]; $this->addManifest($site->handle); if ($fullExport) { $newSite = $this->onBeforeExport($site, $newSite); } return $newSite; }
[ "public", "function", "exportItem", "(", "$", "id", ",", "$", "fullExport", "=", "false", ")", "{", "$", "site", "=", "Craft", "::", "$", "app", "->", "sites", "->", "getSiteById", "(", "$", "id", ")", ";", "$", "newSite", "=", "[", "'name'", "=>",...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Sites.php#L27-L48
dgrigg/Craft-Migration-Manager
src/services/Sites.php
Sites.importItem
public function importItem(Array $data) { $existing = Craft::$app->sites->getSiteByHandle($data['handle']); if ($existing){ $this->mergeUpdates($data, $existing); } $site = $this->createModel($data); $event = $this->onBeforeImport($site, $data); if ($event->isValid){ $result = Craft::$app->sites->saveSite($event->element); if ($result) { $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' site.'); } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' site.'); $this->addError('error', $event->error); return false; } return $result; }
php
public function importItem(Array $data) { $existing = Craft::$app->sites->getSiteByHandle($data['handle']); if ($existing){ $this->mergeUpdates($data, $existing); } $site = $this->createModel($data); $event = $this->onBeforeImport($site, $data); if ($event->isValid){ $result = Craft::$app->sites->saveSite($event->element); if ($result) { $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' site.'); } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' site.'); $this->addError('error', $event->error); return false; } return $result; }
[ "public", "function", "importItem", "(", "Array", "$", "data", ")", "{", "$", "existing", "=", "Craft", "::", "$", "app", "->", "sites", "->", "getSiteByHandle", "(", "$", "data", "[", "'handle'", "]", ")", ";", "if", "(", "$", "existing", ")", "{", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Sites.php#L53-L77
dgrigg/Craft-Migration-Manager
src/services/Sites.php
Sites.createModel
public function createModel(array $data) { $site = new Site(); if (array_key_exists('id', $data)) { $site->id = $data['id']; } $group = $this->getSiteGroup($data['group']); if (!$group){ $group = new SiteGroup(); $group->name = $data['group']; } $data['groupId'] = $group->id; $site->name = $data['name']; $site->handle = $data['handle']; $site->groupId = $data['groupId']; $site->language = $data['language']; $site->hasUrls = $data['hasUrls']; $site->baseUrl = $data['baseUrl']; $site->primary = $data['primary']; $site->sortOrder = $data['sortOrder']; return $site; }
php
public function createModel(array $data) { $site = new Site(); if (array_key_exists('id', $data)) { $site->id = $data['id']; } $group = $this->getSiteGroup($data['group']); if (!$group){ $group = new SiteGroup(); $group->name = $data['group']; } $data['groupId'] = $group->id; $site->name = $data['name']; $site->handle = $data['handle']; $site->groupId = $data['groupId']; $site->language = $data['language']; $site->hasUrls = $data['hasUrls']; $site->baseUrl = $data['baseUrl']; $site->primary = $data['primary']; $site->sortOrder = $data['sortOrder']; return $site; }
[ "public", "function", "createModel", "(", "array", "$", "data", ")", "{", "$", "site", "=", "new", "Site", "(", ")", ";", "if", "(", "array_key_exists", "(", "'id'", ",", "$", "data", ")", ")", "{", "$", "site", "->", "id", "=", "$", "data", "[",...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Sites.php#L82-L106
dgrigg/Craft-Migration-Manager
src/services/Sites.php
Sites.getSiteGroup
private function getSiteGroup($name) { $query = (new Query()) ->select(['id', 'name']) ->from(['{{%sitegroups}}']) ->orderBy(['name' => SORT_DESC]) ->where(['name' => $name]); $result = $query->one(); if ($result){ $group = new SiteGroup(); $group->id = $result['id']; $group->name = $result['name']; return $group; } else { return false; } }
php
private function getSiteGroup($name) { $query = (new Query()) ->select(['id', 'name']) ->from(['{{%sitegroups}}']) ->orderBy(['name' => SORT_DESC]) ->where(['name' => $name]); $result = $query->one(); if ($result){ $group = new SiteGroup(); $group->id = $result['id']; $group->name = $result['name']; return $group; } else { return false; } }
[ "private", "function", "getSiteGroup", "(", "$", "name", ")", "{", "$", "query", "=", "(", "new", "Query", "(", ")", ")", "->", "select", "(", "[", "'id'", ",", "'name'", "]", ")", "->", "from", "(", "[", "'{{%sitegroups}}'", "]", ")", "->", "order...
This function is used vs Craft::$app->sites->getAllGroups() to ensure the id can be returned for newly created groups without a db commit transaction being required @param $name @return bool|SiteGroup
[ "This", "function", "is", "used", "vs", "Craft", "::", "$app", "-", ">", "sites", "-", ">", "getAllGroups", "()", "to", "ensure", "the", "id", "can", "be", "returned", "for", "newly", "created", "groups", "without", "a", "db", "commit", "transaction", "b...
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Sites.php#L124-L144
dgrigg/Craft-Migration-Manager
src/services/Tags.php
Tags.exportItem
public function exportItem($id, $fullExport = false) { $tag = Craft::$app->tags->getTagGroupById($id); if (!$tag) { return false; } $newTag = [ 'name' => $tag->name, 'handle' => $tag->handle, ]; $this->addManifest($tag->handle); if ($fullExport) { $newTag['fieldLayout'] = array(); $newTag['requiredFields'] = array(); $fieldLayout = $tag->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { $newTag['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newTag['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newTag['requiredFields'][] = $tabField->handle; } } } } if ($fullExport) { $newTag = $this->onBeforeExport($tag, $newTag); } return $newTag; }
php
public function exportItem($id, $fullExport = false) { $tag = Craft::$app->tags->getTagGroupById($id); if (!$tag) { return false; } $newTag = [ 'name' => $tag->name, 'handle' => $tag->handle, ]; $this->addManifest($tag->handle); if ($fullExport) { $newTag['fieldLayout'] = array(); $newTag['requiredFields'] = array(); $fieldLayout = $tag->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { $newTag['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newTag['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newTag['requiredFields'][] = $tabField->handle; } } } } if ($fullExport) { $newTag = $this->onBeforeExport($tag, $newTag); } return $newTag; }
[ "public", "function", "exportItem", "(", "$", "id", ",", "$", "fullExport", "=", "false", ")", "{", "$", "tag", "=", "Craft", "::", "$", "app", "->", "tags", "->", "getTagGroupById", "(", "$", "id", ")", ";", "if", "(", "!", "$", "tag", ")", "{",...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Tags.php#L25-L61
dgrigg/Craft-Migration-Manager
src/services/Tags.php
Tags.importItem
public function importItem(Array $data) { $existing = Craft::$app->tags->getTagGroupByHandle($data['handle']); if ($existing) { $this->mergeUpdates($data, $existing); } $tag = $this->createModel($data); $event = $this->onBeforeImport($tag, $data); if ($event->isValid) { $result = Craft::$app->tags->saveTagGroup($event->element); if ($result) { $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' tag.'); } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' tag.'); $this->addError('error', $event->error); return false; } return $result; }
php
public function importItem(Array $data) { $existing = Craft::$app->tags->getTagGroupByHandle($data['handle']); if ($existing) { $this->mergeUpdates($data, $existing); } $tag = $this->createModel($data); $event = $this->onBeforeImport($tag, $data); if ($event->isValid) { $result = Craft::$app->tags->saveTagGroup($event->element); if ($result) { $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' tag.'); } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' tag.'); $this->addError('error', $event->error); return false; } return $result; }
[ "public", "function", "importItem", "(", "Array", "$", "data", ")", "{", "$", "existing", "=", "Craft", "::", "$", "app", "->", "tags", "->", "getTagGroupByHandle", "(", "$", "data", "[", "'handle'", "]", ")", ";", "if", "(", "$", "existing", ")", "{...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Tags.php#L66-L91
dgrigg/Craft-Migration-Manager
src/services/Tags.php
Tags.createModel
public function createModel(array $data) { $tag = new TagGroup(); if (array_key_exists('id', $data)) { $tag->id = $data['id']; } $tag->name = $data['name']; $tag->handle = $data['handle']; if (array_key_exists('fieldLayout', $data)) { $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } else { $this->addError('error', 'Missing field: ' . $field . ' can not add to field layout for Tag: ' . $tag->handle); } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = Tag::class; $tag->fieldLayout = $fieldLayout; } return $tag; }
php
public function createModel(array $data) { $tag = new TagGroup(); if (array_key_exists('id', $data)) { $tag->id = $data['id']; } $tag->name = $data['name']; $tag->handle = $data['handle']; if (array_key_exists('fieldLayout', $data)) { $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } else { $this->addError('error', 'Missing field: ' . $field . ' can not add to field layout for Tag: ' . $tag->handle); } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = Tag::class; $tag->fieldLayout = $fieldLayout; } return $tag; }
[ "public", "function", "createModel", "(", "array", "$", "data", ")", "{", "$", "tag", "=", "new", "TagGroup", "(", ")", ";", "if", "(", "array_key_exists", "(", "'id'", ",", "$", "data", ")", ")", "{", "$", "tag", "->", "id", "=", "$", "data", "[...
@param array $data @return TagGroupModel
[ "@param", "array", "$data" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Tags.php#L107-L149
dgrigg/Craft-Migration-Manager
src/MigrationManager.php
MigrationManager.init
public function init() { parent::init(); self::$plugin = $this; $this->setComponents([ 'migrations' => \firstborn\migrationmanager\services\Migrations::class, 'sites' => \firstborn\migrationmanager\services\Sites::class, 'fields' => \firstborn\migrationmanager\services\Fields::class, 'sections' => \firstborn\migrationmanager\services\Sections::class, 'assetVolumes' => \firstborn\migrationmanager\services\AssetVolumes::class, 'assetTransforms' => \firstborn\migrationmanager\services\AssetTransforms::class, 'globals' => \firstborn\migrationmanager\services\Globals::class, 'tags' => \firstborn\migrationmanager\services\Tags::class, 'categories' => \firstborn\migrationmanager\services\Categories::class, 'routes' => \firstborn\migrationmanager\services\Routes::class, 'userGroups' => \firstborn\migrationmanager\services\UserGroups::class, 'systemMessages' => \firstborn\migrationmanager\services\SystemMessages::class, 'categoriesContent' => \firstborn\migrationmanager\services\CategoriesContent::class, 'entriesContent' => \firstborn\migrationmanager\services\EntriesContent::class, 'globalsContent' => \firstborn\migrationmanager\services\GlobalsContent::class, 'usersContent' => \firstborn\migrationmanager\services\UsersContent::class, ]); // Register our CP routes Event::on( UrlManager::class, UrlManager::EVENT_REGISTER_CP_URL_RULES, function (RegisterUrlRulesEvent $event) { $event->rules['migrationmanager/migrations'] = 'migrationmanager/cp/migrations'; $event->rules['migrationmanager/create'] = 'migrationmanager/cp/index'; $event->rules['migrationmanager'] = 'migrationmanager/cp/index'; } ); // Register variables Event::on( CraftVariable::class, CraftVariable::EVENT_INIT, function (Event $event) { /** @var CraftVariable $variable */ $variable = $event->sender; $variable->set('migrationManager', MigrationManagerVariable::class); } ); // Register actions only if Solo license or user has rights if (Craft::$app->getEdition() > Craft::Solo && (Craft::$app->user->checkPermission('createContentMigrations') == true || Craft::$app->getUser()->getIsAdmin()) || Craft::$app->getEdition() === Craft::Solo) { // Register Element Actions Event::on(Entry::class, Element::EVENT_REGISTER_ACTIONS, function (RegisterElementActionsEvent $event) { $event->actions[] = MigrateEntryElementAction::class; } ); Event::on(Category::class, Element::EVENT_REGISTER_ACTIONS, function (RegisterElementActionsEvent $event) { $event->actions[] = MigrateCategoryElementAction::class; } ); Event::on(User::class, Element::EVENT_REGISTER_ACTIONS, function (RegisterElementActionsEvent $event) { $event->actions[] = MigrateUserElementAction::class; } ); } Event::on( UserPermissions::class, UserPermissions::EVENT_REGISTER_PERMISSIONS, function(RegisterUserPermissionsEvent $event) { $event->permissions['Migration Manager'] = [ 'createContentMigrations' => [ 'label' => 'Create content migrations', ], ]; } ); $request = Craft::$app->getRequest(); if (!$request->getIsConsoleRequest() && $request->getSegment(1) == 'globals'){ $view = Craft::$app->getView(); $view->registerAssetBundle(CpGlobalsAssetBundle::class); $view->registerJs('new Craft.MigrationManagerGlobalsExport();', View::POS_END); } }
php
public function init() { parent::init(); self::$plugin = $this; $this->setComponents([ 'migrations' => \firstborn\migrationmanager\services\Migrations::class, 'sites' => \firstborn\migrationmanager\services\Sites::class, 'fields' => \firstborn\migrationmanager\services\Fields::class, 'sections' => \firstborn\migrationmanager\services\Sections::class, 'assetVolumes' => \firstborn\migrationmanager\services\AssetVolumes::class, 'assetTransforms' => \firstborn\migrationmanager\services\AssetTransforms::class, 'globals' => \firstborn\migrationmanager\services\Globals::class, 'tags' => \firstborn\migrationmanager\services\Tags::class, 'categories' => \firstborn\migrationmanager\services\Categories::class, 'routes' => \firstborn\migrationmanager\services\Routes::class, 'userGroups' => \firstborn\migrationmanager\services\UserGroups::class, 'systemMessages' => \firstborn\migrationmanager\services\SystemMessages::class, 'categoriesContent' => \firstborn\migrationmanager\services\CategoriesContent::class, 'entriesContent' => \firstborn\migrationmanager\services\EntriesContent::class, 'globalsContent' => \firstborn\migrationmanager\services\GlobalsContent::class, 'usersContent' => \firstborn\migrationmanager\services\UsersContent::class, ]); // Register our CP routes Event::on( UrlManager::class, UrlManager::EVENT_REGISTER_CP_URL_RULES, function (RegisterUrlRulesEvent $event) { $event->rules['migrationmanager/migrations'] = 'migrationmanager/cp/migrations'; $event->rules['migrationmanager/create'] = 'migrationmanager/cp/index'; $event->rules['migrationmanager'] = 'migrationmanager/cp/index'; } ); // Register variables Event::on( CraftVariable::class, CraftVariable::EVENT_INIT, function (Event $event) { /** @var CraftVariable $variable */ $variable = $event->sender; $variable->set('migrationManager', MigrationManagerVariable::class); } ); // Register actions only if Solo license or user has rights if (Craft::$app->getEdition() > Craft::Solo && (Craft::$app->user->checkPermission('createContentMigrations') == true || Craft::$app->getUser()->getIsAdmin()) || Craft::$app->getEdition() === Craft::Solo) { // Register Element Actions Event::on(Entry::class, Element::EVENT_REGISTER_ACTIONS, function (RegisterElementActionsEvent $event) { $event->actions[] = MigrateEntryElementAction::class; } ); Event::on(Category::class, Element::EVENT_REGISTER_ACTIONS, function (RegisterElementActionsEvent $event) { $event->actions[] = MigrateCategoryElementAction::class; } ); Event::on(User::class, Element::EVENT_REGISTER_ACTIONS, function (RegisterElementActionsEvent $event) { $event->actions[] = MigrateUserElementAction::class; } ); } Event::on( UserPermissions::class, UserPermissions::EVENT_REGISTER_PERMISSIONS, function(RegisterUserPermissionsEvent $event) { $event->permissions['Migration Manager'] = [ 'createContentMigrations' => [ 'label' => 'Create content migrations', ], ]; } ); $request = Craft::$app->getRequest(); if (!$request->getIsConsoleRequest() && $request->getSegment(1) == 'globals'){ $view = Craft::$app->getView(); $view->registerAssetBundle(CpGlobalsAssetBundle::class); $view->registerJs('new Craft.MigrationManagerGlobalsExport();', View::POS_END); } }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "self", "::", "$", "plugin", "=", "$", "this", ";", "$", "this", "->", "setComponents", "(", "[", "'migrations'", "=>", "\\", "firstborn", "\\", "migrationmanager", "\\...
Set our $plugin static property to this class so that it can be accessed via Test::$plugin Called after the plugin class is instantiated; do any one-time initialization here such as hooks and events. If you have a '/vendor/autoload.php' file, it will be loaded for you automatically; you do not need to load it in your init() method.
[ "Set", "our", "$plugin", "static", "property", "to", "this", "class", "so", "that", "it", "can", "be", "accessed", "via", "Test", "::", "$plugin" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/MigrationManager.php#L73-L160
dgrigg/Craft-Migration-Manager
src/actions/MigrateEntryElementAction.php
MigrateEntryElementAction.performAction
public function performAction(ElementQueryInterface $query): bool { $params['entry'] = []; $elements = $query->all(); foreach ($elements as $element) { $params['entry'][] = $element; } if (MigrationManager::getInstance()->migrations->createContentMigration($params)) { $this->setMessage(Craft::t('app', 'Migration created.')); return true; } else { $this->setMessage(Craft::t('app', 'Migration could not be created.')); return false; } }
php
public function performAction(ElementQueryInterface $query): bool { $params['entry'] = []; $elements = $query->all(); foreach ($elements as $element) { $params['entry'][] = $element; } if (MigrationManager::getInstance()->migrations->createContentMigration($params)) { $this->setMessage(Craft::t('app', 'Migration created.')); return true; } else { $this->setMessage(Craft::t('app', 'Migration could not be created.')); return false; } }
[ "public", "function", "performAction", "(", "ElementQueryInterface", "$", "query", ")", ":", "bool", "{", "$", "params", "[", "'entry'", "]", "=", "[", "]", ";", "$", "elements", "=", "$", "query", "->", "all", "(", ")", ";", "foreach", "(", "$", "el...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/actions/MigrateEntryElementAction.php#L28-L46
dgrigg/Craft-Migration-Manager
src/services/BaseContentMigration.php
BaseContentMigration.onBeforeExportFieldValue
public function onBeforeExportFieldValue($element, $data) { $event = new ExportEvent(array( 'element' => $element, 'value' => $data )); $this->trigger($this::EVENT_BEFORE_EXPORT_FIELD_VALUE, $event); return $event->value; }
php
public function onBeforeExportFieldValue($element, $data) { $event = new ExportEvent(array( 'element' => $element, 'value' => $data )); $this->trigger($this::EVENT_BEFORE_EXPORT_FIELD_VALUE, $event); return $event->value; }
[ "public", "function", "onBeforeExportFieldValue", "(", "$", "element", ",", "$", "data", ")", "{", "$", "event", "=", "new", "ExportEvent", "(", "array", "(", "'element'", "=>", "$", "element", ",", "'value'", "=>", "$", "data", ")", ")", ";", "$", "th...
Fires an 'onBeforeImport' event. @param Event $event $event->params['element'] - model to be imported, manipulate this to change the model before it is saved $event->params['value'] - data used to create the element model @return null
[ "Fires", "an", "onBeforeImport", "event", "." ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/BaseContentMigration.php#L120-L128
dgrigg/Craft-Migration-Manager
src/services/BaseContentMigration.php
BaseContentMigration.onBeforeImportFieldValue
public function onBeforeImportFieldValue($element, $data) { $event = new ImportEvent(array( 'element' => $element, 'value' => $data )); $this->trigger($this::EVENT_BEFORE_IMPORT_FIELD_VALUE, $event); return $event->value; }
php
public function onBeforeImportFieldValue($element, $data) { $event = new ImportEvent(array( 'element' => $element, 'value' => $data )); $this->trigger($this::EVENT_BEFORE_IMPORT_FIELD_VALUE, $event); return $event->value; }
[ "public", "function", "onBeforeImportFieldValue", "(", "$", "element", ",", "$", "data", ")", "{", "$", "event", "=", "new", "ImportEvent", "(", "array", "(", "'element'", "=>", "$", "element", ",", "'value'", "=>", "$", "data", ")", ")", ";", "$", "th...
Fires an 'onBeforeImport' event. @param Event $event $event->params['element'] - model to be imported, manipulate this to change the model before it is saved $event->params['value'] - data used to create the element model @return null
[ "Fires", "an", "onBeforeImport", "event", "." ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/BaseContentMigration.php#L196-L204
dgrigg/Craft-Migration-Manager
src/services/BaseContentMigration.php
BaseContentMigration.localizeData
protected function localizeData(Element $element, Array &$data) { $fieldLayout = $element->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { foreach ($tab->getFields() as $tabField) { $field = Craft::$app->fields->getFieldById($tabField->id); $fieldValue = $element[$field->handle]; if ( in_array ($field->className() , ['craft\fields\Matrix', 'verbb\supertable\fields\SuperTableField', 'benf\neo\Field']) ) { if ($field->localizeBlocks == false) { $items = $fieldValue->getIterator(); $i = 1; foreach ($items as $item) { if (key_exists('new'. $i, $data['fields'][$field->handle])) { $data['fields'][$field->handle][$item->id] = $data['fields'][$field->handle]['new' . $i]; unset($data['fields'][$field->handle]['new' . $i]); } $i++; } } } } } }
php
protected function localizeData(Element $element, Array &$data) { $fieldLayout = $element->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { foreach ($tab->getFields() as $tabField) { $field = Craft::$app->fields->getFieldById($tabField->id); $fieldValue = $element[$field->handle]; if ( in_array ($field->className() , ['craft\fields\Matrix', 'verbb\supertable\fields\SuperTableField', 'benf\neo\Field']) ) { if ($field->localizeBlocks == false) { $items = $fieldValue->getIterator(); $i = 1; foreach ($items as $item) { if (key_exists('new'. $i, $data['fields'][$field->handle])) { $data['fields'][$field->handle][$item->id] = $data['fields'][$field->handle]['new' . $i]; unset($data['fields'][$field->handle]['new' . $i]); } $i++; } } } } } }
[ "protected", "function", "localizeData", "(", "Element", "$", "element", ",", "Array", "&", "$", "data", ")", "{", "$", "fieldLayout", "=", "$", "element", "->", "getFieldLayout", "(", ")", ";", "foreach", "(", "$", "fieldLayout", "->", "getTabs", "(", "...
Look for matrix/supertables/neo that are not localized and update the keys to ensure the site/locale values on child elements remain intact @param BaseElementModel $element @param array $data function foo($method)
[ "Look", "for", "matrix", "/", "supertables", "/", "neo", "that", "are", "not", "localized", "and", "update", "the", "keys", "to", "ensure", "the", "site", "/", "locale", "values", "on", "child", "elements", "remain", "intact" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/BaseContentMigration.php#L426-L448
dgrigg/Craft-Migration-Manager
src/services/UsersContent.php
UsersContent.exportItem
public function exportItem($id, $fullExport = false) { $user = Craft::$app->users->getUserById($id); $this->addManifest($id); if ($user) { $attributes = $user->getAttributes(); unset($attributes['id']); unset($attributes['contentId']); unset($attributes['uid']); unset($attributes['siteId']); $content = array(); $this->getContent($content, $user); $content = array_merge($content, $attributes); $content = $this->onBeforeExport($user, $content); return $content; } return false; }
php
public function exportItem($id, $fullExport = false) { $user = Craft::$app->users->getUserById($id); $this->addManifest($id); if ($user) { $attributes = $user->getAttributes(); unset($attributes['id']); unset($attributes['contentId']); unset($attributes['uid']); unset($attributes['siteId']); $content = array(); $this->getContent($content, $user); $content = array_merge($content, $attributes); $content = $this->onBeforeExport($user, $content); return $content; } return false; }
[ "public", "function", "exportItem", "(", "$", "id", ",", "$", "fullExport", "=", "false", ")", "{", "$", "user", "=", "Craft", "::", "$", "app", "->", "users", "->", "getUserById", "(", "$", "id", ")", ";", "$", "this", "->", "addManifest", "(", "$...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/UsersContent.php#L24-L47
dgrigg/Craft-Migration-Manager
src/services/UsersContent.php
UsersContent.importItem
public function importItem(Array $data) { $user = Craft::$app->users->getUserByUsernameOrEmail($data['username']); if ($user) { $data['id'] = $user->id; $data['contentId'] = $user->contentId; } $user = $this->createModel($data); $this->getSourceIds($data); $this->validateImportValues($data); if (array_key_exists('fields', $data)) { $user->setFieldValues($data['fields']); } $event = $this->onBeforeImport($user, $data); if ($event->isValid) { // save user $result = Craft::$app->getElements()->saveElement($event->element); if ($result) { $groups = $this->getUserGroupIds($data['groups']); Craft::$app->users->assignUserToGroups($user->id, $groups); $permissions = MigrationManagerHelper::getPermissionIds($data['permissions']); Craft::$app->userPermissions->saveUserPermissions($user->id, $permissions); $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['email'] . ' users.'); $this->addError('error', join(',', $event->element->getErrors())); return false; } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' global.'); $this->addError('error', $event->error); return false; } return true; }
php
public function importItem(Array $data) { $user = Craft::$app->users->getUserByUsernameOrEmail($data['username']); if ($user) { $data['id'] = $user->id; $data['contentId'] = $user->contentId; } $user = $this->createModel($data); $this->getSourceIds($data); $this->validateImportValues($data); if (array_key_exists('fields', $data)) { $user->setFieldValues($data['fields']); } $event = $this->onBeforeImport($user, $data); if ($event->isValid) { // save user $result = Craft::$app->getElements()->saveElement($event->element); if ($result) { $groups = $this->getUserGroupIds($data['groups']); Craft::$app->users->assignUserToGroups($user->id, $groups); $permissions = MigrationManagerHelper::getPermissionIds($data['permissions']); Craft::$app->userPermissions->saveUserPermissions($user->id, $permissions); $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['email'] . ' users.'); $this->addError('error', join(',', $event->element->getErrors())); return false; } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' global.'); $this->addError('error', $event->error); return false; } return true; }
[ "public", "function", "importItem", "(", "Array", "$", "data", ")", "{", "$", "user", "=", "Craft", "::", "$", "app", "->", "users", "->", "getUserByUsernameOrEmail", "(", "$", "data", "[", "'username'", "]", ")", ";", "if", "(", "$", "user", ")", "{...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/UsersContent.php#L52-L93
dgrigg/Craft-Migration-Manager
src/services/UsersContent.php
UsersContent.createModel
public function createModel(array $data) { $user = new User(); if (array_key_exists('id', $data)) { $user->id = $data['id']; } $user->setAttributes($data); return $user; }
php
public function createModel(array $data) { $user = new User(); if (array_key_exists('id', $data)) { $user->id = $data['id']; } $user->setAttributes($data); return $user; }
[ "public", "function", "createModel", "(", "array", "$", "data", ")", "{", "$", "user", "=", "new", "User", "(", ")", ";", "if", "(", "array_key_exists", "(", "'id'", ",", "$", "data", ")", ")", "{", "$", "user", "->", "id", "=", "$", "data", "[",...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/UsersContent.php#L98-L108
dgrigg/Craft-Migration-Manager
src/services/UsersContent.php
UsersContent.getContent
protected function getContent(&$content, $element) { parent::getContent($content, $element); $this->getUserGroupHandles($content, $element); $this->getUserPermissionHandles($content, $element); }
php
protected function getContent(&$content, $element) { parent::getContent($content, $element); $this->getUserGroupHandles($content, $element); $this->getUserPermissionHandles($content, $element); }
[ "protected", "function", "getContent", "(", "&", "$", "content", ",", "$", "element", ")", "{", "parent", "::", "getContent", "(", "$", "content", ",", "$", "element", ")", ";", "$", "this", "->", "getUserGroupHandles", "(", "$", "content", ",", "$", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/UsersContent.php#L113-L119
dgrigg/Craft-Migration-Manager
src/services/UsersContent.php
UsersContent.getUserGroupIds
private function getUserGroupIds($groups) { $userGroups = []; foreach ($groups as $group) { $userGroup = Craft::$app->userGroups->getGroupByHandle($group); $userGroups[] = $userGroup->id; } return $userGroups; }
php
private function getUserGroupIds($groups) { $userGroups = []; foreach ($groups as $group) { $userGroup = Craft::$app->userGroups->getGroupByHandle($group); $userGroups[] = $userGroup->id; } return $userGroups; }
[ "private", "function", "getUserGroupIds", "(", "$", "groups", ")", "{", "$", "userGroups", "=", "[", "]", ";", "foreach", "(", "$", "groups", "as", "$", "group", ")", "{", "$", "userGroup", "=", "Craft", "::", "$", "app", "->", "userGroups", "->", "g...
@param array $groups @return array
[ "@param", "array", "$groups" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/UsersContent.php#L126-L136
dgrigg/Craft-Migration-Manager
src/services/AssetVolumes.php
AssetVolumes.exportItem
public function exportItem($id, $fullExport = false) { $volume = Craft::$app->volumes->getVolumeById($id); if (!$volume) { return false; } $this->addManifest($volume->handle); $newVolume = [ 'name' => $volume->name, 'handle' => $volume->handle, 'type' => $volume->className(), 'sortOrder' => $volume->sortOrder, 'typesettings' => $volume->settings, ]; if ($volume->hasUrls){ $newVolume['hasUrls'] = 1; $newVolume['url'] = $volume->url; } if ($fullExport) { $newVolume['fieldLayout'] = array(); $fieldLayout = $volume->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { $newVolume['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newVolume['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newVolume['requiredFields'][] =$tabField->handle; } } } } if ($fullExport) { $newVolume = $this->onBeforeExport($volume, $newVolume); } return $newVolume; }
php
public function exportItem($id, $fullExport = false) { $volume = Craft::$app->volumes->getVolumeById($id); if (!$volume) { return false; } $this->addManifest($volume->handle); $newVolume = [ 'name' => $volume->name, 'handle' => $volume->handle, 'type' => $volume->className(), 'sortOrder' => $volume->sortOrder, 'typesettings' => $volume->settings, ]; if ($volume->hasUrls){ $newVolume['hasUrls'] = 1; $newVolume['url'] = $volume->url; } if ($fullExport) { $newVolume['fieldLayout'] = array(); $fieldLayout = $volume->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { $newVolume['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newVolume['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newVolume['requiredFields'][] =$tabField->handle; } } } } if ($fullExport) { $newVolume = $this->onBeforeExport($volume, $newVolume); } return $newVolume; }
[ "public", "function", "exportItem", "(", "$", "id", ",", "$", "fullExport", "=", "false", ")", "{", "$", "volume", "=", "Craft", "::", "$", "app", "->", "volumes", "->", "getVolumeById", "(", "$", "id", ")", ";", "if", "(", "!", "$", "volume", ")",...
@param int $id @param bool $fullExport @return array|bool
[ "@param", "int", "$id", "@param", "bool", "$fullExport" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/AssetVolumes.php#L29-L71
dgrigg/Craft-Migration-Manager
src/services/AssetVolumes.php
AssetVolumes.importItem
public function importItem(Array $data) { $existing = Craft::$app->volumes->getVolumeByHandle($data['handle']); if ($existing) { $this->mergeUpdates($data, $existing); } $volume = $this->createModel($data); $event = $this->onBeforeImport($volume, $data); if ($event->isValid) { $result = Craft::$app->volumes->saveVolume($event->element); if ($result){ $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Failed to save asset volume.'); $errors = $event->element->getErrors(); foreach($errors as $error) { $this->addError('error', $error); } return false; } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' asset volume.'); $this->addError('error', $event->error); return false; } $result = true; return $result; }
php
public function importItem(Array $data) { $existing = Craft::$app->volumes->getVolumeByHandle($data['handle']); if ($existing) { $this->mergeUpdates($data, $existing); } $volume = $this->createModel($data); $event = $this->onBeforeImport($volume, $data); if ($event->isValid) { $result = Craft::$app->volumes->saveVolume($event->element); if ($result){ $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Failed to save asset volume.'); $errors = $event->element->getErrors(); foreach($errors as $error) { $this->addError('error', $error); } return false; } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' asset volume.'); $this->addError('error', $event->error); return false; } $result = true; return $result; }
[ "public", "function", "importItem", "(", "Array", "$", "data", ")", "{", "$", "existing", "=", "Craft", "::", "$", "app", "->", "volumes", "->", "getVolumeByHandle", "(", "$", "data", "[", "'handle'", "]", ")", ";", "if", "(", "$", "existing", ")", "...
@param array $data @return bool @throws \Exception
[ "@param", "array", "$data" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/AssetVolumes.php#L79-L109
dgrigg/Craft-Migration-Manager
src/services/AssetVolumes.php
AssetVolumes.createModel
public function createModel(Array $data) { $volumes = Craft::$app->getVolumes(); $volume = $volumes->createVolume([ 'id' => array_key_exists('id', $data) ? $data['id'] : null, 'type' => $data['type'], 'name' => $data['name'], 'handle' => $data['handle'], 'hasUrls' => array_key_exists('hasUrls', $data) ? $data['hasUrls'] : false, 'url' => array_key_exists('hasUrls', $data) ? $data['url'] : '', 'sortOrder' => $data['sortOrder'], 'settings' => $data['typesettings'] ]); if (array_key_exists('fieldLayout', $data)) { $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } else { $this->addError('error', 'Missing field: '.$field.' can not add to field layout for Asset Volume: '.$volume->handle); } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = Asset::class; $volume->fieldLayout = $fieldLayout; } return $volume; }
php
public function createModel(Array $data) { $volumes = Craft::$app->getVolumes(); $volume = $volumes->createVolume([ 'id' => array_key_exists('id', $data) ? $data['id'] : null, 'type' => $data['type'], 'name' => $data['name'], 'handle' => $data['handle'], 'hasUrls' => array_key_exists('hasUrls', $data) ? $data['hasUrls'] : false, 'url' => array_key_exists('hasUrls', $data) ? $data['url'] : '', 'sortOrder' => $data['sortOrder'], 'settings' => $data['typesettings'] ]); if (array_key_exists('fieldLayout', $data)) { $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } else { $this->addError('error', 'Missing field: '.$field.' can not add to field layout for Asset Volume: '.$volume->handle); } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = Asset::class; $volume->fieldLayout = $fieldLayout; } return $volume; }
[ "public", "function", "createModel", "(", "Array", "$", "data", ")", "{", "$", "volumes", "=", "Craft", "::", "$", "app", "->", "getVolumes", "(", ")", ";", "$", "volume", "=", "$", "volumes", "->", "createVolume", "(", "[", "'id'", "=>", "array_key_ex...
@param array $data @return VolumeInterface
[ "@param", "array", "$data" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/AssetVolumes.php#L116-L161
dgrigg/Craft-Migration-Manager
src/controllers/CpController.php
CpController.actionIndex
public function actionIndex() { $outstanding = MigrationManager::getInstance()->getBadgeCount(); if ($outstanding){ Craft::$app->getSession()->setError(Craft::t('migrationmanager','There are pending migrations to run')); } return $this->renderTemplate('migrationmanager/index'); }
php
public function actionIndex() { $outstanding = MigrationManager::getInstance()->getBadgeCount(); if ($outstanding){ Craft::$app->getSession()->setError(Craft::t('migrationmanager','There are pending migrations to run')); } return $this->renderTemplate('migrationmanager/index'); }
[ "public", "function", "actionIndex", "(", ")", "{", "$", "outstanding", "=", "MigrationManager", "::", "getInstance", "(", ")", "->", "getBadgeCount", "(", ")", ";", "if", "(", "$", "outstanding", ")", "{", "Craft", "::", "$", "app", "->", "getSession", ...
Index
[ "Index" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/controllers/CpController.php#L19-L26
dgrigg/Craft-Migration-Manager
src/controllers/CpController.php
CpController.actionMigrations
public function actionMigrations() { $migrator = Craft::$app->getContentMigrator(); $pending = $migrator->getNewMigrations(); $applied = $migrator->getMigrationHistory(); return $this->renderTemplate('migrationmanager/migrations', array('pending' => $pending, 'applied' => $applied)); }
php
public function actionMigrations() { $migrator = Craft::$app->getContentMigrator(); $pending = $migrator->getNewMigrations(); $applied = $migrator->getMigrationHistory(); return $this->renderTemplate('migrationmanager/migrations', array('pending' => $pending, 'applied' => $applied)); }
[ "public", "function", "actionMigrations", "(", ")", "{", "$", "migrator", "=", "Craft", "::", "$", "app", "->", "getContentMigrator", "(", ")", ";", "$", "pending", "=", "$", "migrator", "->", "getNewMigrations", "(", ")", ";", "$", "applied", "=", "$", ...
Shows migrations
[ "Shows", "migrations" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/controllers/CpController.php#L31-L37
dgrigg/Craft-Migration-Manager
src/services/AssetTransforms.php
AssetTransforms.exportItem
public function exportItem($id, $fullExport = false) { $transform = Craft::$app->assetTransforms->getTransformById($id); if (!$transform) { return false; } $this->addManifest($transform->handle); $newTransform = [ 'name' => $transform->name, 'handle' => $transform->handle, 'width' => $transform->width, 'height' => $transform->height, 'format' => $transform->format, 'mode' => $transform->mode, 'position' => $transform->position, 'quality' => $transform->quality, 'interlace' => $transform->interlace ]; return $newTransform; }
php
public function exportItem($id, $fullExport = false) { $transform = Craft::$app->assetTransforms->getTransformById($id); if (!$transform) { return false; } $this->addManifest($transform->handle); $newTransform = [ 'name' => $transform->name, 'handle' => $transform->handle, 'width' => $transform->width, 'height' => $transform->height, 'format' => $transform->format, 'mode' => $transform->mode, 'position' => $transform->position, 'quality' => $transform->quality, 'interlace' => $transform->interlace ]; return $newTransform; }
[ "public", "function", "exportItem", "(", "$", "id", ",", "$", "fullExport", "=", "false", ")", "{", "$", "transform", "=", "Craft", "::", "$", "app", "->", "assetTransforms", "->", "getTransformById", "(", "$", "id", ")", ";", "if", "(", "!", "$", "t...
@param int $id @param bool $fullExport @return array|bool
[ "@param", "int", "$id", "@param", "bool", "$fullExport" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/AssetTransforms.php#L27-L49
dgrigg/Craft-Migration-Manager
src/services/UserGroups.php
UserGroups.exportItem
public function exportItem($id, $fullExport = false) { $group = Craft::$app->userGroups->getGroupById($id); if (!$group) { return false; } $newGroup = [ 'name' => $group->name, 'handle' => $group->handle, ]; $this->addManifest($group->handle); if ($fullExport) { $newGroup['fieldLayout'] = array(); $newGroup['requiredFields'] = array(); $fieldLayout = Craft::$app->fields->getLayoutByType(User::class); foreach ($fieldLayout->getTabs() as $tab) { $newGroup['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newGroup['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newGroup['requiredFields'][] = $tabField->handle; } } } $newGroup['permissions'] = $this->getGroupPermissionHandles($id); $newGroup['settings'] = Craft::$app->systemSettings->getSettings('users'); if ($newGroup['settings']['defaultGroup'] != null) { $group = Craft::$app->userGroups->getGroupById($newGroup['settings']['defaultGroup']); $newGroup['settings']['defaultGroup'] = $group->handle; } } if ($fullExport) { $newGroup = $this->onBeforeExport($group, $newGroup); } return $newGroup; }
php
public function exportItem($id, $fullExport = false) { $group = Craft::$app->userGroups->getGroupById($id); if (!$group) { return false; } $newGroup = [ 'name' => $group->name, 'handle' => $group->handle, ]; $this->addManifest($group->handle); if ($fullExport) { $newGroup['fieldLayout'] = array(); $newGroup['requiredFields'] = array(); $fieldLayout = Craft::$app->fields->getLayoutByType(User::class); foreach ($fieldLayout->getTabs() as $tab) { $newGroup['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newGroup['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newGroup['requiredFields'][] = $tabField->handle; } } } $newGroup['permissions'] = $this->getGroupPermissionHandles($id); $newGroup['settings'] = Craft::$app->systemSettings->getSettings('users'); if ($newGroup['settings']['defaultGroup'] != null) { $group = Craft::$app->userGroups->getGroupById($newGroup['settings']['defaultGroup']); $newGroup['settings']['defaultGroup'] = $group->handle; } } if ($fullExport) { $newGroup = $this->onBeforeExport($group, $newGroup); } return $newGroup; }
[ "public", "function", "exportItem", "(", "$", "id", ",", "$", "fullExport", "=", "false", ")", "{", "$", "group", "=", "Craft", "::", "$", "app", "->", "userGroups", "->", "getGroupById", "(", "$", "id", ")", ";", "if", "(", "!", "$", "group", ")",...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/UserGroups.php#L26-L71
dgrigg/Craft-Migration-Manager
src/services/UserGroups.php
UserGroups.importItem
public function importItem(array $data) { $existing = Craft::$app->userGroups->getGroupByHandle($data['handle']); if ($existing) { $this->mergeUpdates($data, $existing); } $userGroup = $this->createModel($data); $event = $this->onBeforeImport($userGroup, $data); if ($event->isValid) { $result = Craft::$app->userGroups->saveGroup($event->element); if ($result) { if (array_key_exists('permissions', $data)) { $permissions = MigrationManagerHelper::getPermissionIds($data['permissions']); if (Craft::$app->userPermissions->saveGroupPermissions($userGroup->id, $permissions)) { } else { $this->addError('error', 'Could not save user group permissions'); } } if (array_key_exists('settings', $data)) { if ($data['settings']['defaultGroup'] != null) { $group = Craft::$app->userGroups->getGroupByHandle($data['settings']['defaultGroup']); $data['settings']['defaultGroup'] = $group->id; } if (Craft::$app->systemSettings->saveSettings('users', $data['settings'])) { } else { $this->addError('error', 'Could not save user group settings'); } } $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' user group.'); } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' user group.'); $this->addError('error', $event->error); return false; } return $result; }
php
public function importItem(array $data) { $existing = Craft::$app->userGroups->getGroupByHandle($data['handle']); if ($existing) { $this->mergeUpdates($data, $existing); } $userGroup = $this->createModel($data); $event = $this->onBeforeImport($userGroup, $data); if ($event->isValid) { $result = Craft::$app->userGroups->saveGroup($event->element); if ($result) { if (array_key_exists('permissions', $data)) { $permissions = MigrationManagerHelper::getPermissionIds($data['permissions']); if (Craft::$app->userPermissions->saveGroupPermissions($userGroup->id, $permissions)) { } else { $this->addError('error', 'Could not save user group permissions'); } } if (array_key_exists('settings', $data)) { if ($data['settings']['defaultGroup'] != null) { $group = Craft::$app->userGroups->getGroupByHandle($data['settings']['defaultGroup']); $data['settings']['defaultGroup'] = $group->id; } if (Craft::$app->systemSettings->saveSettings('users', $data['settings'])) { } else { $this->addError('error', 'Could not save user group settings'); } } $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' user group.'); } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' user group.'); $this->addError('error', $event->error); return false; } return $result; }
[ "public", "function", "importItem", "(", "array", "$", "data", ")", "{", "$", "existing", "=", "Craft", "::", "$", "app", "->", "userGroups", "->", "getGroupByHandle", "(", "$", "data", "[", "'handle'", "]", ")", ";", "if", "(", "$", "existing", ")", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/UserGroups.php#L76-L125
dgrigg/Craft-Migration-Manager
src/services/UserGroups.php
UserGroups.createModel
public function createModel(Array $data) { $userGroup = new UserGroup(); if (array_key_exists('id', $data)) { $userGroup->id = $data['id']; } $userGroup->name = $data['name']; $userGroup->handle = $data['handle']; if (array_key_exists('fieldLayout', $data)) { $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } else { $this->addError('error', 'Missing field: ' . $field . ' can not add to field layout for User Group: ' . $userGroup->handle); } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = User::class; Craft::$app->fields->deleteLayoutsByType(User::class); if (Craft::$app->fields->saveLayout($fieldLayout)) { } else { $this->addError('error', Craft::t('Couldn’t save user fields.')); } } return $userGroup; }
php
public function createModel(Array $data) { $userGroup = new UserGroup(); if (array_key_exists('id', $data)) { $userGroup->id = $data['id']; } $userGroup->name = $data['name']; $userGroup->handle = $data['handle']; if (array_key_exists('fieldLayout', $data)) { $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } else { $this->addError('error', 'Missing field: ' . $field . ' can not add to field layout for User Group: ' . $userGroup->handle); } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = User::class; Craft::$app->fields->deleteLayoutsByType(User::class); if (Craft::$app->fields->saveLayout($fieldLayout)) { } else { $this->addError('error', Craft::t('Couldn’t save user fields.')); } } return $userGroup; }
[ "public", "function", "createModel", "(", "Array", "$", "data", ")", "{", "$", "userGroup", "=", "new", "UserGroup", "(", ")", ";", "if", "(", "array_key_exists", "(", "'id'", ",", "$", "data", ")", ")", "{", "$", "userGroup", "->", "id", "=", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/UserGroups.php#L130-L178
dgrigg/Craft-Migration-Manager
src/services/UserGroups.php
UserGroups.getGroupPermissionHandles
private function getGroupPermissionHandles($id) { $permissions = Craft::$app->userPermissions->getPermissionsByGroupId($id); $permissions = MigrationManagerHelper::getPermissionHandles($permissions); return $permissions; }
php
private function getGroupPermissionHandles($id) { $permissions = Craft::$app->userPermissions->getPermissionsByGroupId($id); $permissions = MigrationManagerHelper::getPermissionHandles($permissions); return $permissions; }
[ "private", "function", "getGroupPermissionHandles", "(", "$", "id", ")", "{", "$", "permissions", "=", "Craft", "::", "$", "app", "->", "userPermissions", "->", "getPermissionsByGroupId", "(", "$", "id", ")", ";", "$", "permissions", "=", "MigrationManagerHelper...
@param int $id @return array
[ "@param", "int", "$id" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/UserGroups.php#L194-L199
dgrigg/Craft-Migration-Manager
src/services/Globals.php
Globals.exportItem
public function exportItem($id, $fullExport = false) { $set = Craft::$app->globals->getSetById($id); if (!$set) { return false; } $newSet = [ 'name' => $set->name, 'handle' => $set->handle, 'fieldLayout' => array(), 'requiredFields' => array(), ]; $this->addManifest($set->handle); $fieldLayout = $set->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { $newSet['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newSet['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newSet['requiredFields'][] = $tabField->handle; } } } if ($fullExport) { $newSet = $this->onBeforeExport($set, $newSet); } return $newSet; }
php
public function exportItem($id, $fullExport = false) { $set = Craft::$app->globals->getSetById($id); if (!$set) { return false; } $newSet = [ 'name' => $set->name, 'handle' => $set->handle, 'fieldLayout' => array(), 'requiredFields' => array(), ]; $this->addManifest($set->handle); $fieldLayout = $set->getFieldLayout(); foreach ($fieldLayout->getTabs() as $tab) { $newSet['fieldLayout'][$tab->name] = array(); foreach ($tab->getFields() as $tabField) { $newSet['fieldLayout'][$tab->name][] = $tabField->handle; if ($tabField->required) { $newSet['requiredFields'][] = $tabField->handle; } } } if ($fullExport) { $newSet = $this->onBeforeExport($set, $newSet); } return $newSet; }
[ "public", "function", "exportItem", "(", "$", "id", ",", "$", "fullExport", "=", "false", ")", "{", "$", "set", "=", "Craft", "::", "$", "app", "->", "globals", "->", "getSetById", "(", "$", "id", ")", ";", "if", "(", "!", "$", "set", ")", "{", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Globals.php#L24-L60
dgrigg/Craft-Migration-Manager
src/services/Globals.php
Globals.importItem
public function importItem(array $data) { $set = $this->createModel($data); $event = $this->onBeforeImport($set, $data); if ($event->isValid) { $result = Craft::$app->globals->saveSet($event->element); if ($result) { $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' global.'); } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' global.'); $this->addError('error', $event->error); return false; } return $result; }
php
public function importItem(array $data) { $set = $this->createModel($data); $event = $this->onBeforeImport($set, $data); if ($event->isValid) { $result = Craft::$app->globals->saveSet($event->element); if ($result) { $this->onAfterImport($event->element, $data); } else { $this->addError('error', 'Could not save the ' . $data['handle'] . ' global.'); } } else { $this->addError('error', 'Error importing ' . $data['handle'] . ' global.'); $this->addError('error', $event->error); return false; } return $result; }
[ "public", "function", "importItem", "(", "array", "$", "data", ")", "{", "$", "set", "=", "$", "this", "->", "createModel", "(", "$", "data", ")", ";", "$", "event", "=", "$", "this", "->", "onBeforeImport", "(", "$", "set", ",", "$", "data", ")", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Globals.php#L65-L85
dgrigg/Craft-Migration-Manager
src/services/Globals.php
Globals.createModel
public function createModel(array $data) { $globalSet = Craft::$app->globals->getSetByHandle($data['handle']); if (!$globalSet instanceof GlobalSet) { $globalSet = new GlobalSet(); } $globalSet->name = $data['name']; $globalSet->handle = $data['handle']; $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } else { $this->addError('error', 'Missing field: ' . $field . ' can not add to field layout for Global: ' . $globalSet->handle); } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = GlobalSet::class; $globalSet->setFieldLayout($fieldLayout); return $globalSet; }
php
public function createModel(array $data) { $globalSet = Craft::$app->globals->getSetByHandle($data['handle']); if (!$globalSet instanceof GlobalSet) { $globalSet = new GlobalSet(); } $globalSet->name = $data['name']; $globalSet->handle = $data['handle']; $requiredFields = array(); if (array_key_exists('requiredFields', $data)) { foreach ($data['requiredFields'] as $handle) { $field = Craft::$app->fields->getFieldByHandle($handle); if ($field) { $requiredFields[] = $field->id; } } } $layout = array(); foreach ($data['fieldLayout'] as $key => $fields) { $fieldIds = array(); foreach ($fields as $field) { $existingField = Craft::$app->fields->getFieldByHandle($field); if ($existingField) { $fieldIds[] = $existingField->id; } else { $this->addError('error', 'Missing field: ' . $field . ' can not add to field layout for Global: ' . $globalSet->handle); } } $layout[$key] = $fieldIds; } $fieldLayout = Craft::$app->fields->assembleLayout($layout, $requiredFields); $fieldLayout->type = GlobalSet::class; $globalSet->setFieldLayout($fieldLayout); return $globalSet; }
[ "public", "function", "createModel", "(", "array", "$", "data", ")", "{", "$", "globalSet", "=", "Craft", "::", "$", "app", "->", "globals", "->", "getSetByHandle", "(", "$", "data", "[", "'handle'", "]", ")", ";", "if", "(", "!", "$", "globalSet", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/dgrigg/Craft-Migration-Manager/blob/dd06eba960635c23778ca2914e7b852ae3d0810a/src/services/Globals.php#L90-L131
yiimaker/yii2-email-templates
src/controllers/DefaultController.php
DefaultController.actionDelete
public function actionDelete($id) { $message = $this->repository->delete($id) ? TemplatesModule::t('Removed successfully') : TemplatesModule::t('Error: banner not removed'); Yii::$app->getSession()->setFlash('yii2-email-templates', $message); return $this->redirect(['index']); }
php
public function actionDelete($id) { $message = $this->repository->delete($id) ? TemplatesModule::t('Removed successfully') : TemplatesModule::t('Error: banner not removed'); Yii::$app->getSession()->setFlash('yii2-email-templates', $message); return $this->redirect(['index']); }
[ "public", "function", "actionDelete", "(", "$", "id", ")", "{", "$", "message", "=", "$", "this", "->", "repository", "->", "delete", "(", "$", "id", ")", "?", "TemplatesModule", "::", "t", "(", "'Removed successfully'", ")", ":", "TemplatesModule", "::", ...
Delete entity. @param int $id @return \yii\web\Response
[ "Delete", "entity", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/controllers/DefaultController.php#L93-L102
yiimaker/yii2-email-templates
src/controllers/DefaultController.php
DefaultController.commonAction
protected function commonAction($model, $redirectUrl, $view) { $request = Yii::$app->getRequest(); if ($request->getIsPost() && $this->repository->save($model, $request->post())) { return $this->redirect($redirectUrl); } return $this->render($view, \compact('model')); }
php
protected function commonAction($model, $redirectUrl, $view) { $request = Yii::$app->getRequest(); if ($request->getIsPost() && $this->repository->save($model, $request->post())) { return $this->redirect($redirectUrl); } return $this->render($view, \compact('model')); }
[ "protected", "function", "commonAction", "(", "$", "model", ",", "$", "redirectUrl", ",", "$", "view", ")", "{", "$", "request", "=", "Yii", "::", "$", "app", "->", "getRequest", "(", ")", ";", "if", "(", "$", "request", "->", "getIsPost", "(", ")", ...
Common code for create and update actions. @param mixed $model @param array $redirectUrl @param string $view @return string|\yii\web\Response
[ "Common", "code", "for", "create", "and", "update", "actions", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/controllers/DefaultController.php#L113-L122
yiimaker/yii2-email-templates
src/Module.php
Module.init
public function init() { parent::init(); if ($this->repository === null) { $this->repository = ['class' => EmailTemplatesRepository::class]; } if ($this->languageProvider === null) { throw new InvalidConfigException('You should configure the language provider'); } $this->registerDependencies(); }
php
public function init() { parent::init(); if ($this->repository === null) { $this->repository = ['class' => EmailTemplatesRepository::class]; } if ($this->languageProvider === null) { throw new InvalidConfigException('You should configure the language provider'); } $this->registerDependencies(); }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "if", "(", "$", "this", "->", "repository", "===", "null", ")", "{", "$", "this", "->", "repository", "=", "[", "'class'", "=>", "EmailTemplatesRepository", "::", "clas...
{{@inheritdoc}}
[ "{{" ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/Module.php#L75-L87
yiimaker/yii2-email-templates
src/Module.php
Module.registerDependencies
protected function registerDependencies() { Yii::$container->setDefinitions([ EmailTemplatesRepositoryInterface::class => $this->repository, LanguageProviderInterface::class => $this->languageProvider, ]); }
php
protected function registerDependencies() { Yii::$container->setDefinitions([ EmailTemplatesRepositoryInterface::class => $this->repository, LanguageProviderInterface::class => $this->languageProvider, ]); }
[ "protected", "function", "registerDependencies", "(", ")", "{", "Yii", "::", "$", "container", "->", "setDefinitions", "(", "[", "EmailTemplatesRepositoryInterface", "::", "class", "=>", "$", "this", "->", "repository", ",", "LanguageProviderInterface", "::", "class...
Register dependencies to DI container.
[ "Register", "dependencies", "to", "DI", "container", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/Module.php#L92-L98
yiimaker/yii2-email-templates
src/migrations/m171119_140800_create_email_template_entities.php
m171119_140800_create_email_template_entities.safeUp
public function safeUp() { $tableOptions = null; if ($this->db->driverName === 'mysql') { /* @link http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci */ $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } // Tables $this->createTable( $this->primaryTableName, [ 'id' => $this->primaryKey()->unsigned(), 'key' => $this->string()->notNull()->unique(), ], $tableOptions ); $this->createTable( $this->translationTableName, [ 'id' => $this->primaryKey()->unsigned(), 'templateId' => $this->integer()->unsigned()->notNull(), 'language' => $this->string(16)->notNull(), 'subject' => $this->string()->notNull(), 'body' => $this->text()->notNull(), 'hint' => $this->string(500), ], $tableOptions ); // Indexes $this->createIndex( 'idx-email_template-key', $this->primaryTableName, 'key', true ); $this->createIndex( 'idx-email_template_translation-templateId', $this->translationTableName, 'templateId' ); $this->createIndex( 'idx-email_template_translation-language', $this->translationTableName, 'language' ); // Foreign keys $this->addForeignKey( 'fk-email_template_translation-email_template', $this->translationTableName, 'templateId', $this->primaryTableName, 'id', 'CASCADE', 'CASCADE' ); }
php
public function safeUp() { $tableOptions = null; if ($this->db->driverName === 'mysql') { /* @link http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci */ $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } // Tables $this->createTable( $this->primaryTableName, [ 'id' => $this->primaryKey()->unsigned(), 'key' => $this->string()->notNull()->unique(), ], $tableOptions ); $this->createTable( $this->translationTableName, [ 'id' => $this->primaryKey()->unsigned(), 'templateId' => $this->integer()->unsigned()->notNull(), 'language' => $this->string(16)->notNull(), 'subject' => $this->string()->notNull(), 'body' => $this->text()->notNull(), 'hint' => $this->string(500), ], $tableOptions ); // Indexes $this->createIndex( 'idx-email_template-key', $this->primaryTableName, 'key', true ); $this->createIndex( 'idx-email_template_translation-templateId', $this->translationTableName, 'templateId' ); $this->createIndex( 'idx-email_template_translation-language', $this->translationTableName, 'language' ); // Foreign keys $this->addForeignKey( 'fk-email_template_translation-email_template', $this->translationTableName, 'templateId', $this->primaryTableName, 'id', 'CASCADE', 'CASCADE' ); }
[ "public", "function", "safeUp", "(", ")", "{", "$", "tableOptions", "=", "null", ";", "if", "(", "$", "this", "->", "db", "->", "driverName", "===", "'mysql'", ")", "{", "/* @link http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and...
{@inheritdoc}
[ "{" ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/migrations/m171119_140800_create_email_template_entities.php#L33-L91
yiimaker/yii2-email-templates
src/migrations/m171119_140800_create_email_template_entities.php
m171119_140800_create_email_template_entities.safeDown
public function safeDown() { $this->dropForeignKey('fk-email_template_translation-email_template', $this->primaryTableName); $this->dropIndex('idx-email_template_translation-language', $this->translationTableName); $this->dropIndex('idx-email_template_translation-templateId', $this->translationTableName); $this->dropIndex('idx-email_template-key', $this->primaryTableName); $this->dropTable($this->translationTableName); $this->dropTable($this->primaryTableName); }
php
public function safeDown() { $this->dropForeignKey('fk-email_template_translation-email_template', $this->primaryTableName); $this->dropIndex('idx-email_template_translation-language', $this->translationTableName); $this->dropIndex('idx-email_template_translation-templateId', $this->translationTableName); $this->dropIndex('idx-email_template-key', $this->primaryTableName); $this->dropTable($this->translationTableName); $this->dropTable($this->primaryTableName); }
[ "public", "function", "safeDown", "(", ")", "{", "$", "this", "->", "dropForeignKey", "(", "'fk-email_template_translation-email_template'", ",", "$", "this", "->", "primaryTableName", ")", ";", "$", "this", "->", "dropIndex", "(", "'idx-email_template_translation-lan...
{@inheritdoc}
[ "{" ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/migrations/m171119_140800_create_email_template_entities.php#L96-L106
yiimaker/yii2-email-templates
src/repositories/EmailTemplatesRepository.php
EmailTemplatesRepository.getByKeyWithTranslation
public function getByKeyWithTranslation($key, $language) { return EmailTemplate::find() ->byKey($key) ->withTranslation($language) ->one(); }
php
public function getByKeyWithTranslation($key, $language) { return EmailTemplate::find() ->byKey($key) ->withTranslation($language) ->one(); }
[ "public", "function", "getByKeyWithTranslation", "(", "$", "key", ",", "$", "language", ")", "{", "return", "EmailTemplate", "::", "find", "(", ")", "->", "byKey", "(", "$", "key", ")", "->", "withTranslation", "(", "$", "language", ")", "->", "one", "("...
Find template by key with translation. @param string $key @param string $language @return EmailTemplate|null
[ "Find", "template", "by", "key", "with", "translation", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/repositories/EmailTemplatesRepository.php#L73-L79
yiimaker/yii2-email-templates
src/repositories/EmailTemplatesRepository.php
EmailTemplatesRepository.getAll
public function getAll($key) { $template = EmailTemplate::find() ->byKey($key) ->with('translations') ->one(); return empty($template->translations) ? null : $template->translations; }
php
public function getAll($key) { $template = EmailTemplate::find() ->byKey($key) ->with('translations') ->one(); return empty($template->translations) ? null : $template->translations; }
[ "public", "function", "getAll", "(", "$", "key", ")", "{", "$", "template", "=", "EmailTemplate", "::", "find", "(", ")", "->", "byKey", "(", "$", "key", ")", "->", "with", "(", "'translations'", ")", "->", "one", "(", ")", ";", "return", "empty", ...
Find all language versions of template by key. @param string $key @return EmailTemplateTranslation[]|null
[ "Find", "all", "language", "versions", "of", "template", "by", "key", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/repositories/EmailTemplatesRepository.php#L88-L96
yiimaker/yii2-email-templates
src/repositories/EmailTemplatesRepository.php
EmailTemplatesRepository.save
public function save($entity, array $data = []) { try { if (empty($data)) { return $entity->save(); } $this->saveInternal($entity, $data); return true; } catch (\Exception $ex) { Yii::$app->getErrorHandler()->logException($ex); } return false; }
php
public function save($entity, array $data = []) { try { if (empty($data)) { return $entity->save(); } $this->saveInternal($entity, $data); return true; } catch (\Exception $ex) { Yii::$app->getErrorHandler()->logException($ex); } return false; }
[ "public", "function", "save", "(", "$", "entity", ",", "array", "$", "data", "=", "[", "]", ")", "{", "try", "{", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "return", "$", "entity", "->", "save", "(", ")", ";", "}", "$", "this", "->...
Save entity. @param EmailTemplate $entity @param array $data @return bool
[ "Save", "entity", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/repositories/EmailTemplatesRepository.php#L137-L152
yiimaker/yii2-email-templates
src/repositories/EmailTemplatesRepository.php
EmailTemplatesRepository.delete
public function delete($id) { try { if ($model = $this->getById($id)) { return (bool) $model->delete(); } } catch (\Exception $ex) { Yii::$app->getErrorHandler()->logException($ex); } return false; }
php
public function delete($id) { try { if ($model = $this->getById($id)) { return (bool) $model->delete(); } } catch (\Exception $ex) { Yii::$app->getErrorHandler()->logException($ex); } return false; }
[ "public", "function", "delete", "(", "$", "id", ")", "{", "try", "{", "if", "(", "$", "model", "=", "$", "this", "->", "getById", "(", "$", "id", ")", ")", "{", "return", "(", "bool", ")", "$", "model", "->", "delete", "(", ")", ";", "}", "}"...
{@inheritdoc}
[ "{" ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/repositories/EmailTemplatesRepository.php#L157-L168
yiimaker/yii2-email-templates
src/repositories/EmailTemplatesRepository.php
EmailTemplatesRepository.deleteObject
public function deleteObject($entity) { try { return (bool) $entity->delete(); } catch (\Exception $ex) { Yii::$app->getErrorHandler()->logException($ex); return false; } }
php
public function deleteObject($entity) { try { return (bool) $entity->delete(); } catch (\Exception $ex) { Yii::$app->getErrorHandler()->logException($ex); return false; } }
[ "public", "function", "deleteObject", "(", "$", "entity", ")", "{", "try", "{", "return", "(", "bool", ")", "$", "entity", "->", "delete", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "Yii", "::", "$", "app", "->", "g...
Removes email template object. @param EmailTemplate $entity @return bool
[ "Removes", "email", "template", "object", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/repositories/EmailTemplatesRepository.php#L177-L186
yiimaker/yii2-email-templates
src/repositories/EmailTemplatesRepository.php
EmailTemplatesRepository.saveInternal
protected function saveInternal(EmailTemplate $entity, array $data) { if ($entity->getIsNewRecord() && !$entity->load($data)) { throw new \DomainException('Cannot load data to primary model'); } foreach ($data[EmailTemplateTranslation::internalFormName()] as $language => $dataSet) { $translationEntity = $entity->getTranslation($language); foreach ($dataSet as $attribute => $translation) { $translationEntity->$attribute = $translation; } } if (!$entity->save()) { throw new \RuntimeException(); } }
php
protected function saveInternal(EmailTemplate $entity, array $data) { if ($entity->getIsNewRecord() && !$entity->load($data)) { throw new \DomainException('Cannot load data to primary model'); } foreach ($data[EmailTemplateTranslation::internalFormName()] as $language => $dataSet) { $translationEntity = $entity->getTranslation($language); foreach ($dataSet as $attribute => $translation) { $translationEntity->$attribute = $translation; } } if (!$entity->save()) { throw new \RuntimeException(); } }
[ "protected", "function", "saveInternal", "(", "EmailTemplate", "$", "entity", ",", "array", "$", "data", ")", "{", "if", "(", "$", "entity", "->", "getIsNewRecord", "(", ")", "&&", "!", "$", "entity", "->", "load", "(", "$", "data", ")", ")", "{", "t...
Save entity to database. @param EmailTemplate $entity @param array $data @throws \DomainException @throws \RuntimeException
[ "Save", "entity", "to", "database", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/repositories/EmailTemplatesRepository.php#L197-L214
yiimaker/yii2-email-templates
src/models/EmailTemplate.php
EmailTemplate.buildMultiply
public static function buildMultiply($entities) { $templates = []; foreach ($entities as $entity) { $templates[$entity->language] = static::buildFromEntity($entity); } return $templates; }
php
public static function buildMultiply($entities) { $templates = []; foreach ($entities as $entity) { $templates[$entity->language] = static::buildFromEntity($entity); } return $templates; }
[ "public", "static", "function", "buildMultiply", "(", "$", "entities", ")", "{", "$", "templates", "=", "[", "]", ";", "foreach", "(", "$", "entities", "as", "$", "entity", ")", "{", "$", "templates", "[", "$", "entity", "->", "language", "]", "=", "...
Build email templates array from entities. @param \ymaker\email\templates\entities\EmailTemplateTranslation[] $entities @return EmailTemplate[]
[ "Build", "email", "templates", "array", "from", "entities", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/models/EmailTemplate.php#L99-L108
yiimaker/yii2-email-templates
src/models/EmailTemplate.php
EmailTemplate.parse
public function parse($data) { if (isset($data['subject'])) { $this->replaceKeys($data['subject'], '_subject'); } if (isset($data['body'])) { $this->replaceKeys($data['body'], '_body'); } }
php
public function parse($data) { if (isset($data['subject'])) { $this->replaceKeys($data['subject'], '_subject'); } if (isset($data['body'])) { $this->replaceKeys($data['body'], '_body'); } }
[ "public", "function", "parse", "(", "$", "data", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "'subject'", "]", ")", ")", "{", "$", "this", "->", "replaceKeys", "(", "$", "data", "[", "'subject'", "]", ",", "'_subject'", ")", ";", "}", "i...
Replace keys to real data in subject and body. @param array $data Array with key-value pairs.
[ "Replace", "keys", "to", "real", "data", "in", "subject", "and", "body", "." ]
train
https://github.com/yiimaker/yii2-email-templates/blob/0dbb8611ecbea503ffaa7f0c5166b78afa0a06c8/src/models/EmailTemplate.php#L128-L137