repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
marcelog/PAMI
src/PAMI/Client/Impl/ClientImpl.php
ClientImpl.messageToResponse
private function messageToResponse($msg) { $response = new ResponseMessage($msg); $actionId = $response->getActionId(); if (is_null($actionId)) { $actionId = $this->lastActionId; $response->setActionId($this->lastActionId); } return $response; }
php
private function messageToResponse($msg) { $response = new ResponseMessage($msg); $actionId = $response->getActionId(); if (is_null($actionId)) { $actionId = $this->lastActionId; $response->setActionId($this->lastActionId); } return $response; }
[ "private", "function", "messageToResponse", "(", "$", "msg", ")", "{", "$", "response", "=", "new", "ResponseMessage", "(", "$", "msg", ")", ";", "$", "actionId", "=", "$", "response", "->", "getActionId", "(", ")", ";", "if", "(", "is_null", "(", "$",...
Returns a ResponseMessage from a raw string that came from asterisk. @param string $msg Raw string. @return \PAMI\Message\Response\ResponseMessage
[ "Returns", "a", "ResponseMessage", "from", "a", "raw", "string", "that", "came", "from", "asterisk", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/Client/Impl/ClientImpl.php#L346-L355
train
marcelog/PAMI
src/PAMI/Client/Impl/ClientImpl.php
ClientImpl.send
public function send(OutgoingMessage $message) { $messageToSend = $message->serialize(); $length = strlen($messageToSend); $this->logger->debug( '------ Sending: ------ ' . "\n" . $messageToSend . '----------' ); $this->lastActionId = $message->getActionId(); if (@fwrite($this->socket, $messageToSend) < $length) { throw new ClientException('Could not send message'); } $read = 0; while ($read <= $this->rTimeout) { $this->process(); $response = $this->getRelated($message); if ($response != false) { $this->lastActionId = false; return $response; } usleep(1000); // 1ms delay if ($this->rTimeout > 0) { $read++; } } throw new ClientException('Read timeout'); }
php
public function send(OutgoingMessage $message) { $messageToSend = $message->serialize(); $length = strlen($messageToSend); $this->logger->debug( '------ Sending: ------ ' . "\n" . $messageToSend . '----------' ); $this->lastActionId = $message->getActionId(); if (@fwrite($this->socket, $messageToSend) < $length) { throw new ClientException('Could not send message'); } $read = 0; while ($read <= $this->rTimeout) { $this->process(); $response = $this->getRelated($message); if ($response != false) { $this->lastActionId = false; return $response; } usleep(1000); // 1ms delay if ($this->rTimeout > 0) { $read++; } } throw new ClientException('Read timeout'); }
[ "public", "function", "send", "(", "OutgoingMessage", "$", "message", ")", "{", "$", "messageToSend", "=", "$", "message", "->", "serialize", "(", ")", ";", "$", "length", "=", "strlen", "(", "$", "messageToSend", ")", ";", "$", "this", "->", "logger", ...
Sends a message to ami. @param \PAMI\Message\OutgoingMessage $message Message to send. @see ClientImpl::send() @throws \PAMI\Client\Exception\ClientException @return \PAMI\Message\Response\ResponseMessage
[ "Sends", "a", "message", "to", "ami", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/Client/Impl/ClientImpl.php#L400-L425
train
marcelog/PAMI
src/PAMI/AsyncAgi/AsyncClientImpl.php
AsyncClientImpl.handle
public function handle(EventMessage $event) { if ($event instanceof \PAMI\Message\Event\AsyncAGIEvent) { if ($event->getCommandId() == $this->lastCommandId) { $this->lastAgiResult = trim($event->getResult()); } } }
php
public function handle(EventMessage $event) { if ($event instanceof \PAMI\Message\Event\AsyncAGIEvent) { if ($event->getCommandId() == $this->lastCommandId) { $this->lastAgiResult = trim($event->getResult()); } } }
[ "public", "function", "handle", "(", "EventMessage", "$", "event", ")", "{", "if", "(", "$", "event", "instanceof", "\\", "PAMI", "\\", "Message", "\\", "Event", "\\", "AsyncAGIEvent", ")", "{", "if", "(", "$", "event", "->", "getCommandId", "(", ")", ...
Handles pami events. @param EventMessage $event @return void
[ "Handles", "pami", "events", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/AsyncAgi/AsyncClientImpl.php#L92-L99
train
marcelog/PAMI
src/PAMI/Message/Action/ActionMessage.php
ActionMessage.setActionID
public function setActionID($actionID) { if (0 == strlen($actionID)) { throw new PAMIException('ActionID cannot be empty.'); } if (strlen($actionID) > 69) { throw new PAMIException('ActionID can be at most 69 characters long.'); } $this->setKey('ActionID', $actionID); }
php
public function setActionID($actionID) { if (0 == strlen($actionID)) { throw new PAMIException('ActionID cannot be empty.'); } if (strlen($actionID) > 69) { throw new PAMIException('ActionID can be at most 69 characters long.'); } $this->setKey('ActionID', $actionID); }
[ "public", "function", "setActionID", "(", "$", "actionID", ")", "{", "if", "(", "0", "==", "strlen", "(", "$", "actionID", ")", ")", "{", "throw", "new", "PAMIException", "(", "'ActionID cannot be empty.'", ")", ";", "}", "if", "(", "strlen", "(", "$", ...
Sets Action ID. The ActionID can be at most 69 characters long, according to {@link https://issues.asterisk.org/jira/browse/14847 Asterisk Issue 14847}. Therefore we'll throw an exception when the ActionID is too long. @param $actionID The Action ID to have this action known by @return void @throws PAMIException When the ActionID is more then 69 characters long
[ "Sets", "Action", "ID", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/Message/Action/ActionMessage.php#L74-L85
train
marcelog/PAMI
src/PAMI/Message/Response/ResponseMessage.php
ResponseMessage.addEvent
public function addEvent(EventMessage $event) { $this->events[] = $event; if (stristr($event->getEventList(), 'complete') !== false || stristr($event->getName(), 'complete') !== false || stristr($event->getName(), 'DBGetResponse') !== false ) { $this->completed = true; } }
php
public function addEvent(EventMessage $event) { $this->events[] = $event; if (stristr($event->getEventList(), 'complete') !== false || stristr($event->getName(), 'complete') !== false || stristr($event->getName(), 'DBGetResponse') !== false ) { $this->completed = true; } }
[ "public", "function", "addEvent", "(", "EventMessage", "$", "event", ")", "{", "$", "this", "->", "events", "[", "]", "=", "$", "event", ";", "if", "(", "stristr", "(", "$", "event", "->", "getEventList", "(", ")", ",", "'complete'", ")", "!==", "fal...
Adds an event to this response. @param EventMessage $event Child event to add. @return void
[ "Adds", "an", "event", "to", "this", "response", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/Message/Response/ResponseMessage.php#L94-L103
train
marcelog/PAMI
src/PAMI/Message/Message.php
Message.getVariable
public function getVariable($key) { if (!isset($this->variables[$key])) { return null; } return $this->variables[$key]; }
php
public function getVariable($key) { if (!isset($this->variables[$key])) { return null; } return $this->variables[$key]; }
[ "public", "function", "getVariable", "(", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "variables", "[", "$", "key", "]", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "variables", "[", "$", "ke...
Returns a variable by name. @param string $key Variable name. @return string
[ "Returns", "a", "variable", "by", "name", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/Message/Message.php#L121-L127
train
marcelog/PAMI
src/PAMI/Message/Message.php
Message.setKey
protected function setKey($key, $value) { $key = strtolower((string)$key); $this->keys[$key] = (string)$value; }
php
protected function setKey($key, $value) { $key = strtolower((string)$key); $this->keys[$key] = (string)$value; }
[ "protected", "function", "setKey", "(", "$", "key", ",", "$", "value", ")", "{", "$", "key", "=", "strtolower", "(", "(", "string", ")", "$", "key", ")", ";", "$", "this", "->", "keys", "[", "$", "key", "]", "=", "(", "string", ")", "$", "value...
Adds a variable to this message. @param string $key Key name (i.e: Action). @param string $value Key value. @return void
[ "Adds", "a", "variable", "to", "this", "message", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/Message/Message.php#L137-L141
train
marcelog/PAMI
src/PAMI/Message/Message.php
Message.getKey
public function getKey($key) { $key = strtolower($key); if (!isset($this->keys[$key])) { return null; } return (string)$this->keys[$key]; }
php
public function getKey($key) { $key = strtolower($key); if (!isset($this->keys[$key])) { return null; } return (string)$this->keys[$key]; }
[ "public", "function", "getKey", "(", "$", "key", ")", "{", "$", "key", "=", "strtolower", "(", "$", "key", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "keys", "[", "$", "key", "]", ")", ")", "{", "return", "null", ";", "}", "re...
Returns a key by name. @param string $key Key name (i.e: Action). @return string
[ "Returns", "a", "key", "by", "name", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/Message/Message.php#L150-L157
train
marcelog/PAMI
src/PAMI/Message/Message.php
Message.serialize
public function serialize() { $result = array(); foreach ($this->getKeys() as $k => $v) { $result[] = $k . ': ' . $v; } foreach ($this->getVariables() as $k => $v) { if (is_array($v)) { foreach ($v as $singleValue) { $result[] = $this->serializeVariable($k, $singleValue); } } else { $result[] = $this->serializeVariable($k, $v); } } $mStr = $this->finishMessage(implode(self::EOL, $result)); return $mStr; }
php
public function serialize() { $result = array(); foreach ($this->getKeys() as $k => $v) { $result[] = $k . ': ' . $v; } foreach ($this->getVariables() as $k => $v) { if (is_array($v)) { foreach ($v as $singleValue) { $result[] = $this->serializeVariable($k, $singleValue); } } else { $result[] = $this->serializeVariable($k, $v); } } $mStr = $this->finishMessage(implode(self::EOL, $result)); return $mStr; }
[ "public", "function", "serialize", "(", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getKeys", "(", ")", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "result", "[", "]", "=", "$", "k", ".", "': '...
Gives a string representation for this message, ready to be sent to ami. @return string
[ "Gives", "a", "string", "representation", "for", "this", "message", "ready", "to", "be", "sent", "to", "ami", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/Message/Message.php#L208-L225
train
marcelog/PAMI
src/PAMI/Message/Event/Factory/Impl/EventFactoryImpl.php
EventFactoryImpl.createFromRaw
public static function createFromRaw($message) { $eventStart = strpos($message, 'Event: ') + 7; $eventEnd = strpos($message, Message::EOL, $eventStart); if ($eventEnd === false) { $eventEnd = strlen($message); } $name = substr($message, $eventStart, $eventEnd - $eventStart); $parts = explode('_', $name); $totalParts = count($parts); for ($i = 0; $i < $totalParts; $i++) { $parts[$i] = ucfirst($parts[$i]); } $name = implode($parts, ''); $className = '\\PAMI\\Message\\Event\\' . $name . 'Event'; if (class_exists($className, true)) { return new $className($message); } return new UnknownEvent($message); }
php
public static function createFromRaw($message) { $eventStart = strpos($message, 'Event: ') + 7; $eventEnd = strpos($message, Message::EOL, $eventStart); if ($eventEnd === false) { $eventEnd = strlen($message); } $name = substr($message, $eventStart, $eventEnd - $eventStart); $parts = explode('_', $name); $totalParts = count($parts); for ($i = 0; $i < $totalParts; $i++) { $parts[$i] = ucfirst($parts[$i]); } $name = implode($parts, ''); $className = '\\PAMI\\Message\\Event\\' . $name . 'Event'; if (class_exists($className, true)) { return new $className($message); } return new UnknownEvent($message); }
[ "public", "static", "function", "createFromRaw", "(", "$", "message", ")", "{", "$", "eventStart", "=", "strpos", "(", "$", "message", ",", "'Event: '", ")", "+", "7", ";", "$", "eventEnd", "=", "strpos", "(", "$", "message", ",", "Message", "::", "EOL...
This is our factory method. @param string $message Literall message as received from ami. @return EventMessage
[ "This", "is", "our", "factory", "method", "." ]
f586d0fcbf7db7952965ccb91e4ed231bd168fb3
https://github.com/marcelog/PAMI/blob/f586d0fcbf7db7952965ccb91e4ed231bd168fb3/src/PAMI/Message/Event/Factory/Impl/EventFactoryImpl.php#L59-L78
train
recca0120/laravel-terminal
src/TerminalServiceProvider.php
TerminalServiceProvider.handlePublishes
protected function handlePublishes() { $this->publishes([ __DIR__.'/../config/terminal.php' => config_path('terminal.php'), ], 'config'); $this->publishes([ __DIR__.'/../resources/views' => base_path('resources/views/vendor/terminal'), ], 'views'); $this->publishes([ __DIR__.'/../public' => public_path('vendor/terminal'), ], 'public'); }
php
protected function handlePublishes() { $this->publishes([ __DIR__.'/../config/terminal.php' => config_path('terminal.php'), ], 'config'); $this->publishes([ __DIR__.'/../resources/views' => base_path('resources/views/vendor/terminal'), ], 'views'); $this->publishes([ __DIR__.'/../public' => public_path('vendor/terminal'), ], 'public'); }
[ "protected", "function", "handlePublishes", "(", ")", "{", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../config/terminal.php'", "=>", "config_path", "(", "'terminal.php'", ")", ",", "]", ",", "'config'", ")", ";", "$", "this", "->", "publis...
handle publishes.
[ "handle", "publishes", "." ]
b9f7ea050e1b29ad28c7b3befbc087f14a379737
https://github.com/recca0120/laravel-terminal/blob/b9f7ea050e1b29ad28c7b3befbc087f14a379737/src/TerminalServiceProvider.php#L85-L98
train
recca0120/laravel-terminal
src/Kernel.php
Kernel.queue
public function queue($command, array $parameters = []) { $app = $this->app->getLaravel(); $app['Illuminate\Contracts\Queue\Queue']->push( 'Illuminate\Foundation\Console\QueuedJob', func_get_args() ); }
php
public function queue($command, array $parameters = []) { $app = $this->app->getLaravel(); $app['Illuminate\Contracts\Queue\Queue']->push( 'Illuminate\Foundation\Console\QueuedJob', func_get_args() ); }
[ "public", "function", "queue", "(", "$", "command", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "$", "app", "=", "$", "this", "->", "app", "->", "getLaravel", "(", ")", ";", "$", "app", "[", "'Illuminate\\Contracts\\Queue\\Queue'", "]", "...
Queue an Artisan console command by name. @param string $command @param array $parameters @return void
[ "Queue", "an", "Artisan", "console", "command", "by", "name", "." ]
b9f7ea050e1b29ad28c7b3befbc087f14a379737
https://github.com/recca0120/laravel-terminal/blob/b9f7ea050e1b29ad28c7b3befbc087f14a379737/src/Kernel.php#L94-L100
train
Athlon1600/php-proxy
src/Plugin/ProxifyPlugin.php
ProxifyPlugin.html_attr
private function html_attr($matches){ // could be empty? $url = trim($matches[2]); $schemes = array('data:', 'magnet:', 'about:', 'javascript:', 'mailto:', 'tel:', 'ios-app:', 'android-app:'); if(starts_with($url, $schemes)){ return $matches[0]; } return str_replace($url, proxify_url($url, $this->base_url), $matches[0]); }
php
private function html_attr($matches){ // could be empty? $url = trim($matches[2]); $schemes = array('data:', 'magnet:', 'about:', 'javascript:', 'mailto:', 'tel:', 'ios-app:', 'android-app:'); if(starts_with($url, $schemes)){ return $matches[0]; } return str_replace($url, proxify_url($url, $this->base_url), $matches[0]); }
[ "private", "function", "html_attr", "(", "$", "matches", ")", "{", "// could be empty?\r", "$", "url", "=", "trim", "(", "$", "matches", "[", "2", "]", ")", ";", "$", "schemes", "=", "array", "(", "'data:'", ",", "'magnet:'", ",", "'about:'", ",", "'ja...
replace src= and href=
[ "replace", "src", "=", "and", "href", "=" ]
580be299a95e8b83d8e7e0b85c5cd906a4a015d8
https://github.com/Athlon1600/php-proxy/blob/580be299a95e8b83d8e7e0b85c5cd906a4a015d8/src/Plugin/ProxifyPlugin.php#L30-L41
train
Athlon1600/php-proxy
src/Http/Request.php
Request.setBody
public function setBody($body, $content_type = false){ // clear old body data $this->post->clear(); $this->files->clear(); // is this form data? if(is_array($body)){ $body = http_build_query($body); } $this->body = (string)$body; // plain text should be: text/plain; charset=UTF-8 if($content_type){ $this->headers->set('content-type', $content_type); } // do it! $this->prepare(); }
php
public function setBody($body, $content_type = false){ // clear old body data $this->post->clear(); $this->files->clear(); // is this form data? if(is_array($body)){ $body = http_build_query($body); } $this->body = (string)$body; // plain text should be: text/plain; charset=UTF-8 if($content_type){ $this->headers->set('content-type', $content_type); } // do it! $this->prepare(); }
[ "public", "function", "setBody", "(", "$", "body", ",", "$", "content_type", "=", "false", ")", "{", "// clear old body data\r", "$", "this", "->", "post", "->", "clear", "(", ")", ";", "$", "this", "->", "files", "->", "clear", "(", ")", ";", "// is t...
will be ignored during PREPARE if post or files contain any values
[ "will", "be", "ignored", "during", "PREPARE", "if", "post", "or", "files", "contain", "any", "values" ]
580be299a95e8b83d8e7e0b85c5cd906a4a015d8
https://github.com/Athlon1600/php-proxy/blob/580be299a95e8b83d8e7e0b85c5cd906a4a015d8/src/Http/Request.php#L193-L213
train
Athlon1600/php-proxy
src/Plugin/AbstractPlugin.php
AbstractPlugin.route
final private function route($event_name, ProxyEvent $event){ $url = $event['request']->getUri(); // url filter provided and current request url does not match it if($this->url_pattern){ if(starts_with($this->url_pattern, '/') && preg_match($this->url_pattern, $url) !== 1){ return; } else if(stripos($url, $this->url_pattern) === false){ return; } } switch($event_name){ case 'request.before_send': $this->onBeforeRequest($event); break; case 'request.sent': $this->onHeadersReceived($event); break; case 'curl.callback.write': $this->onCurlWrite($event); break; case 'request.complete': $this->onCompleted($event); break; } }
php
final private function route($event_name, ProxyEvent $event){ $url = $event['request']->getUri(); // url filter provided and current request url does not match it if($this->url_pattern){ if(starts_with($this->url_pattern, '/') && preg_match($this->url_pattern, $url) !== 1){ return; } else if(stripos($url, $this->url_pattern) === false){ return; } } switch($event_name){ case 'request.before_send': $this->onBeforeRequest($event); break; case 'request.sent': $this->onHeadersReceived($event); break; case 'curl.callback.write': $this->onCurlWrite($event); break; case 'request.complete': $this->onCompleted($event); break; } }
[ "final", "private", "function", "route", "(", "$", "event_name", ",", "ProxyEvent", "$", "event", ")", "{", "$", "url", "=", "$", "event", "[", "'request'", "]", "->", "getUri", "(", ")", ";", "// url filter provided and current request url does not match it\r", ...
dispatch based on filter
[ "dispatch", "based", "on", "filter" ]
580be299a95e8b83d8e7e0b85c5cd906a4a015d8
https://github.com/Athlon1600/php-proxy/blob/580be299a95e8b83d8e7e0b85c5cd906a4a015d8/src/Plugin/AbstractPlugin.php#L48-L78
train
Athlon1600/php-proxy
src/Plugin/CookiePlugin.php
CookiePlugin.onHeadersReceived
public function onHeadersReceived(ProxyEvent $event){ $request = $event['request']; $response = $event['response']; // does the response send any cookies? $set_cookie = $response->headers->get('set-cookie'); if($set_cookie){ // remove set-cookie header and reconstruct it differently $response->headers->remove('set-cookie'); // loop through each set-cookie line foreach( (array)$set_cookie as $line){ // parse cookie data as array from header line $cookie = $this->parse_cookie($line, $request->getUri()); // construct a "proxy cookie" whose name includes the domain to which this cookie belongs to // replace dots with underscores as cookie name can only contain alphanumeric and underscore $cookie_name = sprintf("%s_%s__%s", self::COOKIE_PREFIX, str_replace('.', '_', $cookie['domain']), $cookie['name']); // append a simple name=value cookie to the header - no expiration date means that the cookie will be a session cookie $event['response']->headers->set('set-cookie', $cookie_name.'='.$cookie['value'], false); } } }
php
public function onHeadersReceived(ProxyEvent $event){ $request = $event['request']; $response = $event['response']; // does the response send any cookies? $set_cookie = $response->headers->get('set-cookie'); if($set_cookie){ // remove set-cookie header and reconstruct it differently $response->headers->remove('set-cookie'); // loop through each set-cookie line foreach( (array)$set_cookie as $line){ // parse cookie data as array from header line $cookie = $this->parse_cookie($line, $request->getUri()); // construct a "proxy cookie" whose name includes the domain to which this cookie belongs to // replace dots with underscores as cookie name can only contain alphanumeric and underscore $cookie_name = sprintf("%s_%s__%s", self::COOKIE_PREFIX, str_replace('.', '_', $cookie['domain']), $cookie['name']); // append a simple name=value cookie to the header - no expiration date means that the cookie will be a session cookie $event['response']->headers->set('set-cookie', $cookie_name.'='.$cookie['value'], false); } } }
[ "public", "function", "onHeadersReceived", "(", "ProxyEvent", "$", "event", ")", "{", "$", "request", "=", "$", "event", "[", "'request'", "]", ";", "$", "response", "=", "$", "event", "[", "'response'", "]", ";", "// does the response send any cookies?\r", "$...
cookies received from a target server via set-cookie should be rewritten
[ "cookies", "received", "from", "a", "target", "server", "via", "set", "-", "cookie", "should", "be", "rewritten" ]
580be299a95e8b83d8e7e0b85c5cd906a4a015d8
https://github.com/Athlon1600/php-proxy/blob/580be299a95e8b83d8e7e0b85c5cd906a4a015d8/src/Plugin/CookiePlugin.php#L56-L83
train
Athlon1600/php-proxy
src/Plugin/CookiePlugin.php
CookiePlugin.parse_cookie
private function parse_cookie($line, $url){ $host = parse_url($url, PHP_URL_HOST); $data = array( 'name' => '', 'value' => '', 'domain' => $host, 'path' => '/', 'expires' => 0, 'secure' => false, 'httpOnly' => true ); $line = preg_replace('/^Set-Cookie2?: /i', '', trim($line)); // there should be at least one name=value pair $pairs = array_filter(array_map('trim', explode(';', $line))); foreach($pairs as $index => $comp){ $parts = explode('=', $comp, 2); $key = trim($parts[0]); if(count($parts) == 1){ // secure; HttpOnly; == 1 $data[$key] = true; } else { $value = trim($parts[1]); if($index == 0){ $data['name'] = $key; $data['value'] = $value; } else { $data[$key] = $value; } } } return $data; }
php
private function parse_cookie($line, $url){ $host = parse_url($url, PHP_URL_HOST); $data = array( 'name' => '', 'value' => '', 'domain' => $host, 'path' => '/', 'expires' => 0, 'secure' => false, 'httpOnly' => true ); $line = preg_replace('/^Set-Cookie2?: /i', '', trim($line)); // there should be at least one name=value pair $pairs = array_filter(array_map('trim', explode(';', $line))); foreach($pairs as $index => $comp){ $parts = explode('=', $comp, 2); $key = trim($parts[0]); if(count($parts) == 1){ // secure; HttpOnly; == 1 $data[$key] = true; } else { $value = trim($parts[1]); if($index == 0){ $data['name'] = $key; $data['value'] = $value; } else { $data[$key] = $value; } } } return $data; }
[ "private", "function", "parse_cookie", "(", "$", "line", ",", "$", "url", ")", "{", "$", "host", "=", "parse_url", "(", "$", "url", ",", "PHP_URL_HOST", ")", ";", "$", "data", "=", "array", "(", "'name'", "=>", "''", ",", "'value'", "=>", "''", ","...
adapted from browserkit
[ "adapted", "from", "browserkit" ]
580be299a95e8b83d8e7e0b85c5cd906a4a015d8
https://github.com/Athlon1600/php-proxy/blob/580be299a95e8b83d8e7e0b85c5cd906a4a015d8/src/Plugin/CookiePlugin.php#L86-L129
train
dereuromark/cakephp-queue
src/Model/Table/QueuedJobsTable.php
QueuedJobsTable.createJob
public function createJob($jobType, array $data = null, array $config = []) { $queuedJob = [ 'job_type' => $jobType, 'data' => is_array($data) ? serialize($data) : null, 'job_group' => !empty($config['group']) ? $config['group'] : null, 'notbefore' => !empty($config['notBefore']) ? $this->getDateTime($config['notBefore']) : null, ] + $config; $queuedJob = $this->newEntity($queuedJob); return $this->saveOrFail($queuedJob); }
php
public function createJob($jobType, array $data = null, array $config = []) { $queuedJob = [ 'job_type' => $jobType, 'data' => is_array($data) ? serialize($data) : null, 'job_group' => !empty($config['group']) ? $config['group'] : null, 'notbefore' => !empty($config['notBefore']) ? $this->getDateTime($config['notBefore']) : null, ] + $config; $queuedJob = $this->newEntity($queuedJob); return $this->saveOrFail($queuedJob); }
[ "public", "function", "createJob", "(", "$", "jobType", ",", "array", "$", "data", "=", "null", ",", "array", "$", "config", "=", "[", "]", ")", "{", "$", "queuedJob", "=", "[", "'job_type'", "=>", "$", "jobType", ",", "'data'", "=>", "is_array", "("...
Adds a new job to the queue. Config - priority: 1-10, defaults to 5 - notBefore: Optional date which must not be preceded - group: Used to group similar QueuedJobs - reference: An optional reference string @param string $jobType Job name @param array|null $data Array of data @param array $config Config to save along with the job @return \Queue\Model\Entity\QueuedJob Saved job entity
[ "Adds", "a", "new", "job", "to", "the", "queue", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Model/Table/QueuedJobsTable.php#L155-L166
train
dereuromark/cakephp-queue
src/Model/Table/QueuedJobsTable.php
QueuedJobsTable.getLength
public function getLength($type = null) { $findConf = [ 'conditions' => [ 'completed IS' => null, ], ]; if ($type !== null) { $findConf['conditions']['job_type'] = $type; } return $this->find('all', $findConf)->count(); }
php
public function getLength($type = null) { $findConf = [ 'conditions' => [ 'completed IS' => null, ], ]; if ($type !== null) { $findConf['conditions']['job_type'] = $type; } return $this->find('all', $findConf)->count(); }
[ "public", "function", "getLength", "(", "$", "type", "=", "null", ")", "{", "$", "findConf", "=", "[", "'conditions'", "=>", "[", "'completed IS'", "=>", "null", ",", "]", ",", "]", ";", "if", "(", "$", "type", "!==", "null", ")", "{", "$", "findCo...
Returns the number of items in the queue. Either returns the number of ALL pending jobs, or the number of pending jobs of the passed type. @param string|null $type Job type to Count @return int
[ "Returns", "the", "number", "of", "items", "in", "the", "queue", ".", "Either", "returns", "the", "number", "of", "ALL", "pending", "jobs", "or", "the", "number", "of", "pending", "jobs", "of", "the", "passed", "type", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Model/Table/QueuedJobsTable.php#L199-L210
train
dereuromark/cakephp-queue
src/Model/Table/QueuedJobsTable.php
QueuedJobsTable.markJobDone
public function markJobDone(QueuedJob $job) { $fields = [ 'completed' => $this->getDateTime(), ]; $job = $this->patchEntity($job, $fields); return (bool)$this->save($job); }
php
public function markJobDone(QueuedJob $job) { $fields = [ 'completed' => $this->getDateTime(), ]; $job = $this->patchEntity($job, $fields); return (bool)$this->save($job); }
[ "public", "function", "markJobDone", "(", "QueuedJob", "$", "job", ")", "{", "$", "fields", "=", "[", "'completed'", "=>", "$", "this", "->", "getDateTime", "(", ")", ",", "]", ";", "$", "job", "=", "$", "this", "->", "patchEntity", "(", "$", "job", ...
Mark a job as Completed, removing it from the queue. @param \Queue\Model\Entity\QueuedJob $job Job @return bool Success
[ "Mark", "a", "job", "as", "Completed", "removing", "it", "from", "the", "queue", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Model/Table/QueuedJobsTable.php#L486-L493
train
dereuromark/cakephp-queue
src/Model/Table/QueuedJobsTable.php
QueuedJobsTable.markJobFailed
public function markJobFailed(QueuedJob $job, $failureMessage = null) { $fields = [ 'failed' => $job->failed + 1, 'failure_message' => $failureMessage, ]; $job = $this->patchEntity($job, $fields); return (bool)$this->save($job); }
php
public function markJobFailed(QueuedJob $job, $failureMessage = null) { $fields = [ 'failed' => $job->failed + 1, 'failure_message' => $failureMessage, ]; $job = $this->patchEntity($job, $fields); return (bool)$this->save($job); }
[ "public", "function", "markJobFailed", "(", "QueuedJob", "$", "job", ",", "$", "failureMessage", "=", "null", ")", "{", "$", "fields", "=", "[", "'failed'", "=>", "$", "job", "->", "failed", "+", "1", ",", "'failure_message'", "=>", "$", "failureMessage", ...
Mark a job as Failed, incrementing the failed-counter and Requeueing it. @param \Queue\Model\Entity\QueuedJob $job Job @param string|null $failureMessage Optional message to append to the failure_message field. @return bool Success
[ "Mark", "a", "job", "as", "Failed", "incrementing", "the", "failed", "-", "counter", "and", "Requeueing", "it", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Model/Table/QueuedJobsTable.php#L502-L510
train
dereuromark/cakephp-queue
src/Model/Table/QueuedJobsTable.php
QueuedJobsTable.reset
public function reset($id = null) { $fields = [ 'completed' => null, 'fetched' => null, 'progress' => 0, 'failed' => 0, 'workerkey' => null, 'failure_message' => null, ]; $conditions = [ 'completed IS' => null, ]; if ($id) { $conditions['id'] = $id; } return $this->updateAll($fields, $conditions); }
php
public function reset($id = null) { $fields = [ 'completed' => null, 'fetched' => null, 'progress' => 0, 'failed' => 0, 'workerkey' => null, 'failure_message' => null, ]; $conditions = [ 'completed IS' => null, ]; if ($id) { $conditions['id'] = $id; } return $this->updateAll($fields, $conditions); }
[ "public", "function", "reset", "(", "$", "id", "=", "null", ")", "{", "$", "fields", "=", "[", "'completed'", "=>", "null", ",", "'fetched'", "=>", "null", ",", "'progress'", "=>", "0", ",", "'failed'", "=>", "0", ",", "'workerkey'", "=>", "null", ",...
Reset current jobs @param int|null $id @return int Success
[ "Reset", "current", "jobs" ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Model/Table/QueuedJobsTable.php#L519-L536
train
dereuromark/cakephp-queue
src/Model/Table/QueuedJobsTable.php
QueuedJobsTable.key
public function key() { if ($this->_key !== null) { return $this->_key; } $this->_key = sha1(microtime()); if (!$this->_key) { throw new RuntimeException('Invalid key generated'); } return $this->_key; }
php
public function key() { if ($this->_key !== null) { return $this->_key; } $this->_key = sha1(microtime()); if (!$this->_key) { throw new RuntimeException('Invalid key generated'); } return $this->_key; }
[ "public", "function", "key", "(", ")", "{", "if", "(", "$", "this", "->", "_key", "!==", "null", ")", "{", "return", "$", "this", "->", "_key", ";", "}", "$", "this", "->", "_key", "=", "sha1", "(", "microtime", "(", ")", ")", ";", "if", "(", ...
Generates a unique Identifier for the current worker thread. Useful to identify the currently running processes for this thread. @return string Identifier
[ "Generates", "a", "unique", "Identifier", "for", "the", "current", "worker", "thread", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Model/Table/QueuedJobsTable.php#L705-L715
train
dereuromark/cakephp-queue
src/Model/Table/QueuedJobsTable.php
QueuedJobsTable.getProcesses
public function getProcesses($forThisServer = false) { /** @var \Queue\Model\Table\QueueProcessesTable $QueueProcesses */ $QueueProcesses = TableRegistry::getTableLocator()->get('Queue.QueueProcesses'); $query = $QueueProcesses->findActive() ->where(['terminate' => false]); if ($forThisServer) { $query = $query->where(['server' => $QueueProcesses->buildServerString()]); } $processes = $query ->enableHydration(false) ->find('list', ['keyField' => 'pid', 'valueField' => 'modified']) ->all() ->toArray(); return $processes; }
php
public function getProcesses($forThisServer = false) { /** @var \Queue\Model\Table\QueueProcessesTable $QueueProcesses */ $QueueProcesses = TableRegistry::getTableLocator()->get('Queue.QueueProcesses'); $query = $QueueProcesses->findActive() ->where(['terminate' => false]); if ($forThisServer) { $query = $query->where(['server' => $QueueProcesses->buildServerString()]); } $processes = $query ->enableHydration(false) ->find('list', ['keyField' => 'pid', 'valueField' => 'modified']) ->all() ->toArray(); return $processes; }
[ "public", "function", "getProcesses", "(", "$", "forThisServer", "=", "false", ")", "{", "/** @var \\Queue\\Model\\Table\\QueueProcessesTable $QueueProcesses */", "$", "QueueProcesses", "=", "TableRegistry", "::", "getTableLocator", "(", ")", "->", "get", "(", "'Queue.Que...
Gets all active processes. $forThisServer only works for DB approach. @param bool $forThisServer @return array
[ "Gets", "all", "active", "processes", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Model/Table/QueuedJobsTable.php#L746-L762
train
dereuromark/cakephp-queue
src/Model/Table/QueuedJobsTable.php
QueuedJobsTable._getDriverName
protected function _getDriverName() { $className = explode('\\', $this->getConnection()->config()['driver']); $name = end($className); return $name; }
php
protected function _getDriverName() { $className = explode('\\', $this->getConnection()->config()['driver']); $name = end($className); return $name; }
[ "protected", "function", "_getDriverName", "(", ")", "{", "$", "className", "=", "explode", "(", "'\\\\'", ",", "$", "this", "->", "getConnection", "(", ")", "->", "config", "(", ")", "[", "'driver'", "]", ")", ";", "$", "name", "=", "end", "(", "$",...
get the name of the driver @return string
[ "get", "the", "name", "of", "the", "driver" ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Model/Table/QueuedJobsTable.php#L813-L818
train
dereuromark/cakephp-queue
src/Shell/Task/QueueEmailTask.php
QueueEmailTask.add
public function add() { $this->err('Queue Email Task cannot be added via Console.'); $this->out('Please use createJob() on the QueuedTask Model to create a Proper Email Task.'); $this->out('The Data Array should look something like this:'); $this->out(var_export([ 'settings' => [ 'to' => 'email@example.com', 'subject' => 'Email Subject', 'from' => 'system@example.com', 'template' => 'sometemplate', ], 'content' => 'hello world', ], true)); $this->out('Alternativly, you can pass the whole EmailLib to directly use it.'); }
php
public function add() { $this->err('Queue Email Task cannot be added via Console.'); $this->out('Please use createJob() on the QueuedTask Model to create a Proper Email Task.'); $this->out('The Data Array should look something like this:'); $this->out(var_export([ 'settings' => [ 'to' => 'email@example.com', 'subject' => 'Email Subject', 'from' => 'system@example.com', 'template' => 'sometemplate', ], 'content' => 'hello world', ], true)); $this->out('Alternativly, you can pass the whole EmailLib to directly use it.'); }
[ "public", "function", "add", "(", ")", "{", "$", "this", "->", "err", "(", "'Queue Email Task cannot be added via Console.'", ")", ";", "$", "this", "->", "out", "(", "'Please use createJob() on the QueuedTask Model to create a Proper Email Task.'", ")", ";", "$", "this...
"Add" the task, not possible for QueueEmailTask @return void
[ "Add", "the", "task", "not", "possible", "for", "QueueEmailTask" ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/Task/QueueEmailTask.php#L43-L57
train
dereuromark/cakephp-queue
src/Shell/Task/QueueMonitorExampleTask.php
QueueMonitorExampleTask.run
public function run(array $data, $jobId) { $this->hr(); $this->out('CakePHP Queue MonitorExample task.'); $this->hr(); $this->doMonitoring(); $this->success(' -> Success, the MonitorExample Job was run. <-'); }
php
public function run(array $data, $jobId) { $this->hr(); $this->out('CakePHP Queue MonitorExample task.'); $this->hr(); $this->doMonitoring(); $this->success(' -> Success, the MonitorExample Job was run. <-'); }
[ "public", "function", "run", "(", "array", "$", "data", ",", "$", "jobId", ")", "{", "$", "this", "->", "hr", "(", ")", ";", "$", "this", "->", "out", "(", "'CakePHP Queue MonitorExample task.'", ")", ";", "$", "this", "->", "hr", "(", ")", ";", "$...
MonitorExample run function. This function is executed, when a worker is executing a task. The return parameter will determine, if the task will be marked completed, or be requeued. @param array $data The array passed to QueuedJobsTable::createJob() @param int $jobId The id of the QueuedJob entity @return void
[ "MonitorExample", "run", "function", ".", "This", "function", "is", "executed", "when", "a", "worker", "is", "executing", "a", "task", ".", "The", "return", "parameter", "will", "determine", "if", "the", "task", "will", "be", "marked", "completed", "or", "be...
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/Task/QueueMonitorExampleTask.php#L54-L62
train
dereuromark/cakephp-queue
src/Queue/TaskFinder.php
TaskFinder.allAppAndPluginTasks
public function allAppAndPluginTasks() { if ($this->tasks !== null) { return $this->tasks; } $paths = App::path('Shell/Task'); $this->tasks = []; foreach ($paths as $path) { $Folder = new Folder($path); $this->tasks = $this->getAppPaths($Folder); } $plugins = Plugin::loaded(); foreach ($plugins as $plugin) { $pluginPaths = App::path('Shell/Task', $plugin); foreach ($pluginPaths as $pluginPath) { $Folder = new Folder($pluginPath); $pluginTasks = $this->getPluginPaths($Folder, $plugin); $this->tasks = array_merge($this->tasks, $pluginTasks); } } return $this->tasks; }
php
public function allAppAndPluginTasks() { if ($this->tasks !== null) { return $this->tasks; } $paths = App::path('Shell/Task'); $this->tasks = []; foreach ($paths as $path) { $Folder = new Folder($path); $this->tasks = $this->getAppPaths($Folder); } $plugins = Plugin::loaded(); foreach ($plugins as $plugin) { $pluginPaths = App::path('Shell/Task', $plugin); foreach ($pluginPaths as $pluginPath) { $Folder = new Folder($pluginPath); $pluginTasks = $this->getPluginPaths($Folder, $plugin); $this->tasks = array_merge($this->tasks, $pluginTasks); } } return $this->tasks; }
[ "public", "function", "allAppAndPluginTasks", "(", ")", "{", "if", "(", "$", "this", "->", "tasks", "!==", "null", ")", "{", "return", "$", "this", "->", "tasks", ";", "}", "$", "paths", "=", "App", "::", "path", "(", "'Shell/Task'", ")", ";", "$", ...
Returns all possible Queue tasks. Makes sure that app tasks are prioritized over plugin ones. @return array
[ "Returns", "all", "possible", "Queue", "tasks", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Queue/TaskFinder.php#L23-L46
train
dereuromark/cakephp-queue
src/Shell/Task/QueueExecuteTask.php
QueueExecuteTask.run
public function run(array $data, $jobId) { $data += [ 'command' => null, 'params' => [], 'redirect' => true, 'escape' => true, 'accepted' => [static::CODE_SUCCESS], ]; if ($data['escape']) { $data['command'] = escapeshellcmd($data['command']); } if ($data['params']) { $params = $data['params']; if ($data['escape']) { foreach ($params as $key => $value) { $params[$key] = escapeshellcmd($value); } } $data['command'] .= ' ' . implode(' ', $params); } $this->out('Executing: `' . $data['command'] . '`'); $command = $data['command']; if ($data['redirect']) { $command .= ' 2>&1'; } exec($command, $output, $returnCode); $this->nl(); $this->out($output); $acceptedReturnCodes = $data['accepted']; $success = !$acceptedReturnCodes || in_array($returnCode, $acceptedReturnCodes, true); if (!$success) { $this->err('Error (code ' . $returnCode . ')', static::VERBOSE); } else { $this->success('Success (code ' . $returnCode . ')', static::VERBOSE); } if (!$success) { throw new QueueException('Failed with error code ' . $returnCode . ': `' . $data['command'] . '`'); } }
php
public function run(array $data, $jobId) { $data += [ 'command' => null, 'params' => [], 'redirect' => true, 'escape' => true, 'accepted' => [static::CODE_SUCCESS], ]; if ($data['escape']) { $data['command'] = escapeshellcmd($data['command']); } if ($data['params']) { $params = $data['params']; if ($data['escape']) { foreach ($params as $key => $value) { $params[$key] = escapeshellcmd($value); } } $data['command'] .= ' ' . implode(' ', $params); } $this->out('Executing: `' . $data['command'] . '`'); $command = $data['command']; if ($data['redirect']) { $command .= ' 2>&1'; } exec($command, $output, $returnCode); $this->nl(); $this->out($output); $acceptedReturnCodes = $data['accepted']; $success = !$acceptedReturnCodes || in_array($returnCode, $acceptedReturnCodes, true); if (!$success) { $this->err('Error (code ' . $returnCode . ')', static::VERBOSE); } else { $this->success('Success (code ' . $returnCode . ')', static::VERBOSE); } if (!$success) { throw new QueueException('Failed with error code ' . $returnCode . ': `' . $data['command'] . '`'); } }
[ "public", "function", "run", "(", "array", "$", "data", ",", "$", "jobId", ")", "{", "$", "data", "+=", "[", "'command'", "=>", "null", ",", "'params'", "=>", "[", "]", ",", "'redirect'", "=>", "true", ",", "'escape'", "=>", "true", ",", "'accepted'"...
Run function. This function is executed, when a worker is executing a task. The return parameter will determine, if the task will be marked completed, or be requeued. @param array $data The array passed to QueuedJobsTable::createJob() @param int $jobId The id of the QueuedJob entity @return void @throws \Queue\Model\QueueException
[ "Run", "function", ".", "This", "function", "is", "executed", "when", "a", "worker", "is", "executing", "a", "task", ".", "The", "return", "parameter", "will", "determine", "if", "the", "task", "will", "be", "marked", "completed", "or", "be", "requeued", "...
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/Task/QueueExecuteTask.php#L63-L108
train
dereuromark/cakephp-queue
src/Shell/Task/QueueSuperExampleTask.php
QueueSuperExampleTask.run
public function run(array $data, $jobId) { $this->hr(); $this->out('CakePHP Queue SuperExample task.'); $this->hr(); $this->success(' -> Success, the SuperExample Job was run. <-'); // Lets create an Example task on successful execution $this->QueuedJobs->createJob('Example'); }
php
public function run(array $data, $jobId) { $this->hr(); $this->out('CakePHP Queue SuperExample task.'); $this->hr(); $this->success(' -> Success, the SuperExample Job was run. <-'); // Lets create an Example task on successful execution $this->QueuedJobs->createJob('Example'); }
[ "public", "function", "run", "(", "array", "$", "data", ",", "$", "jobId", ")", "{", "$", "this", "->", "hr", "(", ")", ";", "$", "this", "->", "out", "(", "'CakePHP Queue SuperExample task.'", ")", ";", "$", "this", "->", "hr", "(", ")", ";", "$",...
SuperExample run function. This function is executed, when a worker is executing a task. The return parameter will determine, if the task will be marked completed, or be requeued. @param array $data The array passed to QueuedJobsTable::createJob() @param int $jobId The id of the QueuedJob entity @return void
[ "SuperExample", "run", "function", ".", "This", "function", "is", "executed", "when", "a", "worker", "is", "executing", "a", "task", ".", "The", "return", "parameter", "will", "determine", "if", "the", "task", "will", "be", "marked", "completed", "or", "be",...
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/Task/QueueSuperExampleTask.php#L58-L66
train
dereuromark/cakephp-queue
src/Model/Table/QueueProcessesTable.php
QueueProcessesTable.buildServerString
public function buildServerString() { $serverName = env('SERVER_NAME') ?: gethostname(); if (!$serverName) { $user = env('USER'); $logName = env('LOGNAME'); if ($user || $logName) { $serverName = $user . '@' . $logName; } } return $serverName ?: null; }
php
public function buildServerString() { $serverName = env('SERVER_NAME') ?: gethostname(); if (!$serverName) { $user = env('USER'); $logName = env('LOGNAME'); if ($user || $logName) { $serverName = $user . '@' . $logName; } } return $serverName ?: null; }
[ "public", "function", "buildServerString", "(", ")", "{", "$", "serverName", "=", "env", "(", "'SERVER_NAME'", ")", "?", ":", "gethostname", "(", ")", ";", "if", "(", "!", "$", "serverName", ")", "{", "$", "user", "=", "env", "(", "'USER'", ")", ";",...
Use ENV to control the server name of the servers run workers with. export SERVER_NAME=myserver1 This way you can deploy separately and only end the processes of that server. @return string|null
[ "Use", "ENV", "to", "control", "the", "server", "name", "of", "the", "servers", "run", "workers", "with", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Model/Table/QueueProcessesTable.php#L222-L233
train
dereuromark/cakephp-queue
src/Controller/Admin/QueueController.php
QueueController.reset
public function reset() { $this->request->allowMethod('post'); $this->QueuedJobs->reset(); $message = __d('queue', 'OK'); $this->Flash->success($message); return $this->redirect(['action' => 'index']); }
php
public function reset() { $this->request->allowMethod('post'); $this->QueuedJobs->reset(); $message = __d('queue', 'OK'); $this->Flash->success($message); return $this->redirect(['action' => 'index']); }
[ "public", "function", "reset", "(", ")", "{", "$", "this", "->", "request", "->", "allowMethod", "(", "'post'", ")", ";", "$", "this", "->", "QueuedJobs", "->", "reset", "(", ")", ";", "$", "message", "=", "__d", "(", "'queue'", ",", "'OK'", ")", "...
Mark all failed jobs as ready for re-run. @return \Cake\Http\Response @throws \Cake\Http\Exception\MethodNotAllowedException when not posted
[ "Mark", "all", "failed", "jobs", "as", "ready", "for", "re", "-", "run", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Controller/Admin/QueueController.php#L140-L148
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell.initialize
public function initialize() { $taskFinder = new TaskFinder(); $this->tasks = $taskFinder->allAppAndPluginTasks(); parent::initialize(); $this->loadModel('Queue.QueueProcesses'); }
php
public function initialize() { $taskFinder = new TaskFinder(); $this->tasks = $taskFinder->allAppAndPluginTasks(); parent::initialize(); $this->loadModel('Queue.QueueProcesses'); }
[ "public", "function", "initialize", "(", ")", "{", "$", "taskFinder", "=", "new", "TaskFinder", "(", ")", ";", "$", "this", "->", "tasks", "=", "$", "taskFinder", "->", "allAppAndPluginTasks", "(", ")", ";", "parent", "::", "initialize", "(", ")", ";", ...
Overwrite shell initialize to dynamically load all Queue Related Tasks. @return void
[ "Overwrite", "shell", "initialize", "to", "dynamically", "load", "all", "Queue", "Related", "Tasks", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L68-L75
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell.clean
public function clean() { if (!Configure::read('Queue.cleanuptimeout')) { $this->abort('You disabled cleanuptimout in config. Aborting.'); } $this->out('Deleting old jobs, that have finished before ' . date('Y-m-d H:i:s', time() - (int)Configure::read('Queue.cleanuptimeout'))); $this->QueuedJobs->cleanOldJobs(); $this->QueueProcesses->cleanEndedProcesses(); }
php
public function clean() { if (!Configure::read('Queue.cleanuptimeout')) { $this->abort('You disabled cleanuptimout in config. Aborting.'); } $this->out('Deleting old jobs, that have finished before ' . date('Y-m-d H:i:s', time() - (int)Configure::read('Queue.cleanuptimeout'))); $this->QueuedJobs->cleanOldJobs(); $this->QueueProcesses->cleanEndedProcesses(); }
[ "public", "function", "clean", "(", ")", "{", "if", "(", "!", "Configure", "::", "read", "(", "'Queue.cleanuptimeout'", ")", ")", "{", "$", "this", "->", "abort", "(", "'You disabled cleanuptimout in config. Aborting.'", ")", ";", "}", "$", "this", "->", "ou...
Manually trigger a Finished job cleanup. @return void
[ "Manually", "trigger", "a", "Finished", "job", "cleanup", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L331-L339
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell.end
public function end($in = null) { $processes = $this->QueuedJobs->getProcesses($in === 'server'); if (!$processes) { $this->out('No processes found'); return; } $this->out(count($processes) . ' processes:'); foreach ($processes as $process => $timestamp) { $this->out(' - ' . $process . ' (last run @ ' . (new FrozenTime($timestamp)) . ')'); } $options = array_keys($processes); $options[] = 'all'; if ($in === null) { $in = $this->in('Process', $options, 'all'); } if ($in === 'all' || $in === 'server') { foreach ($processes as $process => $timestamp) { $this->QueuedJobs->endProcess($process); } $this->out('All ' . count($processes) . ' processes ended.'); return; } $this->QueuedJobs->endProcess($in); }
php
public function end($in = null) { $processes = $this->QueuedJobs->getProcesses($in === 'server'); if (!$processes) { $this->out('No processes found'); return; } $this->out(count($processes) . ' processes:'); foreach ($processes as $process => $timestamp) { $this->out(' - ' . $process . ' (last run @ ' . (new FrozenTime($timestamp)) . ')'); } $options = array_keys($processes); $options[] = 'all'; if ($in === null) { $in = $this->in('Process', $options, 'all'); } if ($in === 'all' || $in === 'server') { foreach ($processes as $process => $timestamp) { $this->QueuedJobs->endProcess($process); } $this->out('All ' . count($processes) . ' processes ended.'); return; } $this->QueuedJobs->endProcess($in); }
[ "public", "function", "end", "(", "$", "in", "=", "null", ")", "{", "$", "processes", "=", "$", "this", "->", "QueuedJobs", "->", "getProcesses", "(", "$", "in", "===", "'server'", ")", ";", "if", "(", "!", "$", "processes", ")", "{", "$", "this", ...
Gracefully end running workers when deploying. Use $in - all: to end all workers on all servers - server: to end the ones on this server @param string|null $in @return void
[ "Gracefully", "end", "running", "workers", "when", "deploying", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L351-L381
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell.rerun
public function rerun($type, $reference = null) { $this->out('Rerunning...'); $count = $this->QueuedJobs->rerun($type, $reference); $this->success($count . ' jobs reset for re-run.'); }
php
public function rerun($type, $reference = null) { $this->out('Rerunning...'); $count = $this->QueuedJobs->rerun($type, $reference); $this->success($count . ' jobs reset for re-run.'); }
[ "public", "function", "rerun", "(", "$", "type", ",", "$", "reference", "=", "null", ")", "{", "$", "this", "->", "out", "(", "'Rerunning...'", ")", ";", "$", "count", "=", "$", "this", "->", "QueuedJobs", "->", "rerun", "(", "$", "type", ",", "$",...
Manually reset already successfully run jobs for re-run. Careful, this should not be done with non-idempotent jobs. This is mainly useful for debugging and local development, if you have to run sth again. @param string $type @param string|null $reference @return void
[ "Manually", "reset", "already", "successfully", "run", "jobs", "for", "re", "-", "run", ".", "Careful", "this", "should", "not", "be", "done", "with", "non", "-", "idempotent", "jobs", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L443-L449
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell.settings
public function settings() { $this->out('Current Settings:'); $conf = (array)Configure::read('Queue'); foreach ($conf as $key => $val) { if ($val === false) { $val = 'no'; } if ($val === true) { $val = 'yes'; } $this->out('* ' . $key . ': ' . print_r($val, true)); } $this->out(); $status = $this->QueueProcesses->status(); $this->out('Current running workers: ' . ($status ? $status['workers'] : '-')); $this->out('Last run: ' . ($status ? $status['time']->nice() : '-')); }
php
public function settings() { $this->out('Current Settings:'); $conf = (array)Configure::read('Queue'); foreach ($conf as $key => $val) { if ($val === false) { $val = 'no'; } if ($val === true) { $val = 'yes'; } $this->out('* ' . $key . ': ' . print_r($val, true)); } $this->out(); $status = $this->QueueProcesses->status(); $this->out('Current running workers: ' . ($status ? $status['workers'] : '-')); $this->out('Last run: ' . ($status ? $status['time']->nice() : '-')); }
[ "public", "function", "settings", "(", ")", "{", "$", "this", "->", "out", "(", "'Current Settings:'", ")", ";", "$", "conf", "=", "(", "array", ")", "Configure", "::", "read", "(", "'Queue'", ")", ";", "foreach", "(", "$", "conf", "as", "$", "key", ...
Display current settings @return void
[ "Display", "current", "settings" ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L456-L474
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell.stats
public function stats() { $this->out('Jobs currently in the queue:'); $types = $this->QueuedJobs->getTypes()->toArray(); foreach ($types as $type) { $this->out(' ' . str_pad($type, 20, ' ', STR_PAD_RIGHT) . ': ' . $this->QueuedJobs->getLength($type)); } $this->hr(); $this->out('Total unfinished jobs: ' . $this->QueuedJobs->getLength()); $this->out('Running workers (processes): ' . $this->QueueProcesses->findActive()->count()); $this->out('Server name: ' . $this->QueueProcesses->buildServerString()); $this->hr(); $this->out('Finished job statistics:'); $data = $this->QueuedJobs->getStats(); foreach ($data as $item) { $this->out(' ' . $item['job_type'] . ': '); $this->out(' Finished Jobs in Database: ' . $item['num']); $this->out(' Average Job existence : ' . str_pad(Number::precision($item['alltime']), 8, ' ', STR_PAD_LEFT) . 's'); $this->out(' Average Execution delay : ' . str_pad(Number::precision($item['fetchdelay']), 8, ' ', STR_PAD_LEFT) . 's'); $this->out(' Average Execution time : ' . str_pad(Number::precision($item['runtime']), 8, ' ', STR_PAD_LEFT) . 's'); } }
php
public function stats() { $this->out('Jobs currently in the queue:'); $types = $this->QueuedJobs->getTypes()->toArray(); foreach ($types as $type) { $this->out(' ' . str_pad($type, 20, ' ', STR_PAD_RIGHT) . ': ' . $this->QueuedJobs->getLength($type)); } $this->hr(); $this->out('Total unfinished jobs: ' . $this->QueuedJobs->getLength()); $this->out('Running workers (processes): ' . $this->QueueProcesses->findActive()->count()); $this->out('Server name: ' . $this->QueueProcesses->buildServerString()); $this->hr(); $this->out('Finished job statistics:'); $data = $this->QueuedJobs->getStats(); foreach ($data as $item) { $this->out(' ' . $item['job_type'] . ': '); $this->out(' Finished Jobs in Database: ' . $item['num']); $this->out(' Average Job existence : ' . str_pad(Number::precision($item['alltime']), 8, ' ', STR_PAD_LEFT) . 's'); $this->out(' Average Execution delay : ' . str_pad(Number::precision($item['fetchdelay']), 8, ' ', STR_PAD_LEFT) . 's'); $this->out(' Average Execution time : ' . str_pad(Number::precision($item['runtime']), 8, ' ', STR_PAD_LEFT) . 's'); } }
[ "public", "function", "stats", "(", ")", "{", "$", "this", "->", "out", "(", "'Jobs currently in the queue:'", ")", ";", "$", "types", "=", "$", "this", "->", "QueuedJobs", "->", "getTypes", "(", ")", "->", "toArray", "(", ")", ";", "foreach", "(", "$"...
Display some statistics about Finished Jobs. @return void
[ "Display", "some", "statistics", "about", "Finished", "Jobs", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L481-L502
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell.getOptionParser
public function getOptionParser() { $subcommandParser = [ 'options' => [ /* 'dry-run'=> array( 'short' => 'd', 'help' => 'Dry run the update, no jobs will actually be added.', 'boolean' => true ), */ ], ]; $subcommandParserFull = $subcommandParser; $subcommandParserFull['options']['group'] = [ 'short' => 'g', 'help' => 'Group (comma separated list possible)', 'default' => null, ]; $subcommandParserFull['options']['type'] = [ 'short' => 't', 'help' => 'Type (comma separated list possible)', 'default' => null, ]; $rerunParser = $subcommandParser; $rerunParser['arguments'] = [ 'type' => [ 'help' => 'Job type. You need to specify one.', 'required' => true, ], 'reference' => [ 'help' => 'Reference.', 'required' => false, ], ]; return parent::getOptionParser() ->setDescription($this->_getDescription()) ->addSubcommand('clean', [ 'help' => 'Remove old jobs (cleanup)', 'parser' => $subcommandParser, ]) ->addSubcommand('add', [ 'help' => 'Add Job', 'parser' => $subcommandParser, ]) ->addSubcommand('stats', [ 'help' => 'Stats', 'parser' => $subcommandParserFull, ]) ->addSubcommand('settings', [ 'help' => 'Settings', 'parser' => $subcommandParserFull, ]) ->addSubcommand('reset', [ 'help' => 'Manually reset (failed) jobs for re-run.', 'parser' => $subcommandParserFull, ]) ->addSubcommand('rerun', [ 'help' => 'Manually rerun (successfully) run job.', 'parser' => $rerunParser, ]) ->addSubcommand('hard_reset', [ 'help' => 'Hard reset queue (remove all jobs)', 'parser' => $subcommandParserFull, ]) ->addSubcommand('end', [ 'help' => 'Manually end a worker.', 'parser' => $subcommandParserFull, ]) ->addSubcommand('kill', [ 'help' => 'Manually kill a worker.', 'parser' => $subcommandParserFull, ]) ->addSubcommand('runworker', [ 'help' => 'Run Worker', 'parser' => $subcommandParserFull, ]); }
php
public function getOptionParser() { $subcommandParser = [ 'options' => [ /* 'dry-run'=> array( 'short' => 'd', 'help' => 'Dry run the update, no jobs will actually be added.', 'boolean' => true ), */ ], ]; $subcommandParserFull = $subcommandParser; $subcommandParserFull['options']['group'] = [ 'short' => 'g', 'help' => 'Group (comma separated list possible)', 'default' => null, ]; $subcommandParserFull['options']['type'] = [ 'short' => 't', 'help' => 'Type (comma separated list possible)', 'default' => null, ]; $rerunParser = $subcommandParser; $rerunParser['arguments'] = [ 'type' => [ 'help' => 'Job type. You need to specify one.', 'required' => true, ], 'reference' => [ 'help' => 'Reference.', 'required' => false, ], ]; return parent::getOptionParser() ->setDescription($this->_getDescription()) ->addSubcommand('clean', [ 'help' => 'Remove old jobs (cleanup)', 'parser' => $subcommandParser, ]) ->addSubcommand('add', [ 'help' => 'Add Job', 'parser' => $subcommandParser, ]) ->addSubcommand('stats', [ 'help' => 'Stats', 'parser' => $subcommandParserFull, ]) ->addSubcommand('settings', [ 'help' => 'Settings', 'parser' => $subcommandParserFull, ]) ->addSubcommand('reset', [ 'help' => 'Manually reset (failed) jobs for re-run.', 'parser' => $subcommandParserFull, ]) ->addSubcommand('rerun', [ 'help' => 'Manually rerun (successfully) run job.', 'parser' => $rerunParser, ]) ->addSubcommand('hard_reset', [ 'help' => 'Hard reset queue (remove all jobs)', 'parser' => $subcommandParserFull, ]) ->addSubcommand('end', [ 'help' => 'Manually end a worker.', 'parser' => $subcommandParserFull, ]) ->addSubcommand('kill', [ 'help' => 'Manually kill a worker.', 'parser' => $subcommandParserFull, ]) ->addSubcommand('runworker', [ 'help' => 'Run Worker', 'parser' => $subcommandParserFull, ]); }
[ "public", "function", "getOptionParser", "(", ")", "{", "$", "subcommandParser", "=", "[", "'options'", "=>", "[", "/*\n\t\t\t\t'dry-run'=> array(\n\t\t\t\t\t'short' => 'd',\n\t\t\t\t\t'help' => 'Dry run the update, no jobs will actually be added.',\n\t\t\t\t\t'boolean' => true\n\t\t\t\t),...
Get option parser method to parse commandline options @return \Cake\Console\ConsoleOptionParser
[ "Get", "option", "parser", "method", "to", "parse", "commandline", "options" ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L521-L599
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell._log
protected function _log($message, $pid = null, $addDetails = true) { if (!Configure::read('Queue.log')) { return; } if ($addDetails) { $timeNeeded = $this->_timeNeeded(); $memoryUsage = $this->_memoryUsage(); $message .= ' [' . $timeNeeded . ', ' . $memoryUsage . ']'; } if ($pid) { $message .= ' (pid ' . $pid . ')'; } Log::write('info', $message, ['scope' => 'queue']); }
php
protected function _log($message, $pid = null, $addDetails = true) { if (!Configure::read('Queue.log')) { return; } if ($addDetails) { $timeNeeded = $this->_timeNeeded(); $memoryUsage = $this->_memoryUsage(); $message .= ' [' . $timeNeeded . ', ' . $memoryUsage . ']'; } if ($pid) { $message .= ' (pid ' . $pid . ')'; } Log::write('info', $message, ['scope' => 'queue']); }
[ "protected", "function", "_log", "(", "$", "message", ",", "$", "pid", "=", "null", ",", "$", "addDetails", "=", "true", ")", "{", "if", "(", "!", "Configure", "::", "read", "(", "'Queue.log'", ")", ")", "{", "return", ";", "}", "if", "(", "$", "...
Timestamped log. @param string $message Log type @param string|null $pid PID of the process @param bool $addDetails @return void
[ "Timestamped", "log", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L609-L624
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell._getTaskConf
protected function _getTaskConf() { if (!is_array($this->_taskConf)) { $this->_taskConf = []; foreach ($this->tasks as $task) { list($pluginName, $taskName) = pluginSplit($task); $this->_taskConf[$taskName]['name'] = substr($taskName, 5); $this->_taskConf[$taskName]['plugin'] = $pluginName; if (property_exists($this->{$taskName}, 'timeout')) { $this->_taskConf[$taskName]['timeout'] = $this->{$taskName}->timeout; } else { $this->_taskConf[$taskName]['timeout'] = Config::defaultworkertimeout(); } if (property_exists($this->{$taskName}, 'retries')) { $this->_taskConf[$taskName]['retries'] = $this->{$taskName}->retries; } else { $this->_taskConf[$taskName]['retries'] = Config::defaultworkerretries(); } if (property_exists($this->{$taskName}, 'rate')) { $this->_taskConf[$taskName]['rate'] = $this->{$taskName}->rate; } } } return $this->_taskConf; }
php
protected function _getTaskConf() { if (!is_array($this->_taskConf)) { $this->_taskConf = []; foreach ($this->tasks as $task) { list($pluginName, $taskName) = pluginSplit($task); $this->_taskConf[$taskName]['name'] = substr($taskName, 5); $this->_taskConf[$taskName]['plugin'] = $pluginName; if (property_exists($this->{$taskName}, 'timeout')) { $this->_taskConf[$taskName]['timeout'] = $this->{$taskName}->timeout; } else { $this->_taskConf[$taskName]['timeout'] = Config::defaultworkertimeout(); } if (property_exists($this->{$taskName}, 'retries')) { $this->_taskConf[$taskName]['retries'] = $this->{$taskName}->retries; } else { $this->_taskConf[$taskName]['retries'] = Config::defaultworkerretries(); } if (property_exists($this->{$taskName}, 'rate')) { $this->_taskConf[$taskName]['rate'] = $this->{$taskName}->rate; } } } return $this->_taskConf; }
[ "protected", "function", "_getTaskConf", "(", ")", "{", "if", "(", "!", "is_array", "(", "$", "this", "->", "_taskConf", ")", ")", "{", "$", "this", "->", "_taskConf", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "tasks", "as", "$", "task...
Returns a List of available QueueTasks and their individual configurations. @return array
[ "Returns", "a", "List", "of", "available", "QueueTasks", "and", "their", "individual", "configurations", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L652-L676
train
dereuromark/cakephp-queue
src/Shell/QueueShell.php
QueueShell._setPhpTimeout
protected function _setPhpTimeout() { $timeLimit = (int)Configure::readOrFail('Queue.workermaxruntime') * 100; if (Configure::read('Queue.workertimeout') !== null) { $timeLimit = (int)Configure::read('Queue.workertimeout'); } set_time_limit($timeLimit); }
php
protected function _setPhpTimeout() { $timeLimit = (int)Configure::readOrFail('Queue.workermaxruntime') * 100; if (Configure::read('Queue.workertimeout') !== null) { $timeLimit = (int)Configure::read('Queue.workertimeout'); } set_time_limit($timeLimit); }
[ "protected", "function", "_setPhpTimeout", "(", ")", "{", "$", "timeLimit", "=", "(", "int", ")", "Configure", "::", "readOrFail", "(", "'Queue.workermaxruntime'", ")", "*", "100", ";", "if", "(", "Configure", "::", "read", "(", "'Queue.workertimeout'", ")", ...
Makes sure accidental overriding isn't possible, uses workermaxruntime times 100 by default. @return void
[ "Makes", "sure", "accidental", "overriding", "isn", "t", "possible", "uses", "workermaxruntime", "times", "100", "by", "default", "." ]
71645ec87efcae8f8a579354d83d9bfd052ec0a1
https://github.com/dereuromark/cakephp-queue/blob/71645ec87efcae8f8a579354d83d9bfd052ec0a1/src/Shell/QueueShell.php#L816-L823
train
plank/laravel-mediable
src/SourceAdapters/RemoteUrlAdapter.php
RemoteUrlAdapter.getHeader
private function getHeader($key) { if (! $this->headers) { $this->headers = $this->getHeaders(); } if (array_key_exists($key, $this->headers)) { //if redirects encountered, return the final values if (is_array($this->headers[$key])) { return end($this->headers[$key]); } else { return $this->headers[$key]; } } }
php
private function getHeader($key) { if (! $this->headers) { $this->headers = $this->getHeaders(); } if (array_key_exists($key, $this->headers)) { //if redirects encountered, return the final values if (is_array($this->headers[$key])) { return end($this->headers[$key]); } else { return $this->headers[$key]; } } }
[ "private", "function", "getHeader", "(", "$", "key", ")", "{", "if", "(", "!", "$", "this", "->", "headers", ")", "{", "$", "this", "->", "headers", "=", "$", "this", "->", "getHeaders", "(", ")", ";", "}", "if", "(", "array_key_exists", "(", "$", ...
Read a header value by name from the remote content. @param mixed $key Header name @return mixed
[ "Read", "a", "header", "value", "by", "name", "from", "the", "remote", "content", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/SourceAdapters/RemoteUrlAdapter.php#L110-L123
train
plank/laravel-mediable
src/HandlesMediaUploadExceptions.php
HandlesMediaUploadExceptions.transformMediaUploadException
protected function transformMediaUploadException(Exception $e) { if ($e instanceof MediaUploadException) { $status_code = $this->getStatusCodeForMediaUploadException($e); return new HttpException($status_code, $e->getMessage(), $e); } return $e; }
php
protected function transformMediaUploadException(Exception $e) { if ($e instanceof MediaUploadException) { $status_code = $this->getStatusCodeForMediaUploadException($e); return new HttpException($status_code, $e->getMessage(), $e); } return $e; }
[ "protected", "function", "transformMediaUploadException", "(", "Exception", "$", "e", ")", "{", "if", "(", "$", "e", "instanceof", "MediaUploadException", ")", "{", "$", "status_code", "=", "$", "this", "->", "getStatusCodeForMediaUploadException", "(", "$", "e", ...
Transform a MediaUploadException into an HttpException. @param \Exception $e @return \Symfony\Component\HttpKernel\Exception\HttpException
[ "Transform", "a", "MediaUploadException", "into", "an", "HttpException", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/HandlesMediaUploadExceptions.php#L55-L63
train
plank/laravel-mediable
src/HandlesMediaUploadExceptions.php
HandlesMediaUploadExceptions.getStatusCodeForMediaUploadException
private function getStatusCodeForMediaUploadException(MediaUploadException $e) { foreach ($this->status_codes as $status_code => $exceptions) { if (in_array(get_class($e), $exceptions)) { return $status_code; } } return 500; }
php
private function getStatusCodeForMediaUploadException(MediaUploadException $e) { foreach ($this->status_codes as $status_code => $exceptions) { if (in_array(get_class($e), $exceptions)) { return $status_code; } } return 500; }
[ "private", "function", "getStatusCodeForMediaUploadException", "(", "MediaUploadException", "$", "e", ")", "{", "foreach", "(", "$", "this", "->", "status_codes", "as", "$", "status_code", "=>", "$", "exceptions", ")", "{", "if", "(", "in_array", "(", "get_class...
Get the appropriate HTTP status code for the exception. @param \Plank\Mediable\Exceptions\MediaUploadException $e @return integer
[ "Get", "the", "appropriate", "HTTP", "status", "code", "for", "the", "exception", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/HandlesMediaUploadExceptions.php#L71-L80
train
plank/laravel-mediable
src/MediableCollection.php
MediableCollection.loadMedia
public function loadMedia($tags = [], $match_all = false) { $tags = (array) $tags; if (empty($tags)) { return $this->load('media'); } if ($match_all) { return $this->loadMediaMatchAll($tags); } $closure = function (MorphToMany $q) use ($tags) { $this->wherePivotTagIn($q, $tags); }; $closure = Closure::bind($closure, $this->first(), $this->first()); return $this->load(['media' => $closure]); }
php
public function loadMedia($tags = [], $match_all = false) { $tags = (array) $tags; if (empty($tags)) { return $this->load('media'); } if ($match_all) { return $this->loadMediaMatchAll($tags); } $closure = function (MorphToMany $q) use ($tags) { $this->wherePivotTagIn($q, $tags); }; $closure = Closure::bind($closure, $this->first(), $this->first()); return $this->load(['media' => $closure]); }
[ "public", "function", "loadMedia", "(", "$", "tags", "=", "[", "]", ",", "$", "match_all", "=", "false", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "tags", ";", "if", "(", "empty", "(", "$", "tags", ")", ")", "{", "return", "$", "this"...
Lazy eager load media attached to items in the collection. @param string|string[] $tags If one or more tags are specified, only media attached to those tags will be loaded. @param bool $match_all If true, only load media attached to all tags simultaneously @return $this
[ "Lazy", "eager", "load", "media", "attached", "to", "items", "in", "the", "collection", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediableCollection.php#L23-L41
train
plank/laravel-mediable
src/MediableCollection.php
MediableCollection.loadMediaMatchAll
public function loadMediaMatchAll($tags = []) { $tags = (array) $tags; $closure = function (MorphToMany $q) use ($tags) { $this->addMatchAllToEagerLoadQuery($q, $tags); }; $closure = Closure::bind($closure, $this->first(), $this->first()); return $this->load(['media' => $closure]); }
php
public function loadMediaMatchAll($tags = []) { $tags = (array) $tags; $closure = function (MorphToMany $q) use ($tags) { $this->addMatchAllToEagerLoadQuery($q, $tags); }; $closure = Closure::bind($closure, $this->first(), $this->first()); return $this->load(['media' => $closure]); }
[ "public", "function", "loadMediaMatchAll", "(", "$", "tags", "=", "[", "]", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "tags", ";", "$", "closure", "=", "function", "(", "MorphToMany", "$", "q", ")", "use", "(", "$", "tags", ")", "{", "$...
Lazy eager load media attached to items in the collection bound all of the provided tags simultaneously. @param string|string[] $tags If one or more tags are specified, only media attached to those tags will be loaded. @return $this
[ "Lazy", "eager", "load", "media", "attached", "to", "items", "in", "the", "collection", "bound", "all", "of", "the", "provided", "tags", "simultaneously", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediableCollection.php#L49-L58
train
plank/laravel-mediable
src/Helpers/File.php
File.readableSize
public static function readableSize($bytes, $precision = 1) { static $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; if ($bytes === 0) { return '0 '.$units[0]; } $exponent = floor(log($bytes, 1024)); $value = $bytes / pow(1024, $exponent); return round($value, $precision).' '.$units[$exponent]; }
php
public static function readableSize($bytes, $precision = 1) { static $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; if ($bytes === 0) { return '0 '.$units[0]; } $exponent = floor(log($bytes, 1024)); $value = $bytes / pow(1024, $exponent); return round($value, $precision).' '.$units[$exponent]; }
[ "public", "static", "function", "readableSize", "(", "$", "bytes", ",", "$", "precision", "=", "1", ")", "{", "static", "$", "units", "=", "[", "'B'", ",", "'KB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", ",", "'PB'", "]", ";", "if", "(", "$", "byt...
Generate a human readable bytecount string. @param int $bytes @param int $precision @return string
[ "Generate", "a", "human", "readable", "bytecount", "string", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Helpers/File.php#L35-L45
train
plank/laravel-mediable
src/MediaMover.php
MediaMover.move
public function move(Media $media, $directory, $filename = null) { $storage = $this->filesystem->disk($media->disk); if ($filename) { $filename = $this->removeExtensionFromFilename($filename, $media->extension); } else { $filename = $media->filename; } $directory = trim($directory, '/'); $target_path = $directory.'/'.$filename.'.'.$media->extension; if ($storage->has($target_path)) { throw MediaMoveException::destinationExists($target_path); } $storage->move($media->getDiskPath(), $target_path); $media->filename = $filename; $media->directory = $directory; $media->save(); }
php
public function move(Media $media, $directory, $filename = null) { $storage = $this->filesystem->disk($media->disk); if ($filename) { $filename = $this->removeExtensionFromFilename($filename, $media->extension); } else { $filename = $media->filename; } $directory = trim($directory, '/'); $target_path = $directory.'/'.$filename.'.'.$media->extension; if ($storage->has($target_path)) { throw MediaMoveException::destinationExists($target_path); } $storage->move($media->getDiskPath(), $target_path); $media->filename = $filename; $media->directory = $directory; $media->save(); }
[ "public", "function", "move", "(", "Media", "$", "media", ",", "$", "directory", ",", "$", "filename", "=", "null", ")", "{", "$", "storage", "=", "$", "this", "->", "filesystem", "->", "disk", "(", "$", "media", "->", "disk", ")", ";", "if", "(", ...
Move the file to a new location on disk. Will invoke the `save()` method on the model after the associated file has been moved to prevent synchronization errors @param \Plank\Mediable\Media $media @param string $directory directory relative to disk root @param string $filename filename. Do not include extension @return void @throws \Plank\Mediable\Exceptions\MediaMoveException If attempting to change the file extension or a file with the same name already exists at the destination
[ "Move", "the", "file", "to", "a", "new", "location", "on", "disk", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaMover.php#L39-L61
train
plank/laravel-mediable
src/MediaMover.php
MediaMover.copyTo
public function copyTo(Media $media, $directory, $filename = null) { $storage = $this->filesystem->disk($media->disk); if ($filename) { $filename = $this->removeExtensionFromFilename($filename, $media->extension); } else { $filename = $media->filename; } $directory = trim($directory, '/'); $target_path = $directory.'/'.$filename.'.'.$media->extension; if ($storage->has($target_path)) { throw MediaMoveException::destinationExists($target_path); } try { $storage->copy($media->getDiskPath(), $target_path); } catch (\Exception $exception) { throw MediaMoveException::failedToCopy($media->getDiskPath(), $target_path); } // now we copy the Media object /** @var Media $newMedia */ $newMedia = $media->replicate(); $newMedia->filename = $filename; $newMedia->directory = $directory; $newMedia->save(); return $newMedia; }
php
public function copyTo(Media $media, $directory, $filename = null) { $storage = $this->filesystem->disk($media->disk); if ($filename) { $filename = $this->removeExtensionFromFilename($filename, $media->extension); } else { $filename = $media->filename; } $directory = trim($directory, '/'); $target_path = $directory.'/'.$filename.'.'.$media->extension; if ($storage->has($target_path)) { throw MediaMoveException::destinationExists($target_path); } try { $storage->copy($media->getDiskPath(), $target_path); } catch (\Exception $exception) { throw MediaMoveException::failedToCopy($media->getDiskPath(), $target_path); } // now we copy the Media object /** @var Media $newMedia */ $newMedia = $media->replicate(); $newMedia->filename = $filename; $newMedia->directory = $directory; $newMedia->save(); return $newMedia; }
[ "public", "function", "copyTo", "(", "Media", "$", "media", ",", "$", "directory", ",", "$", "filename", "=", "null", ")", "{", "$", "storage", "=", "$", "this", "->", "filesystem", "->", "disk", "(", "$", "media", "->", "disk", ")", ";", "if", "("...
Copy the file from one Media object to another one. This method creates a new Media object as well as duplicates the associated file on the disk. @param \Plank\Mediable\Media $media The media to copy from @param string $directory directory relative to disk root @param string $filename optional filename. Do not include extension @return \Plank\Mediable\Media @throws \Plank\Mediable\Exceptions\MediaMoveException If a file with the same name already exists at the destination or it fails to copy the file
[ "Copy", "the", "file", "from", "one", "Media", "object", "to", "another", "one", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaMover.php#L76-L108
train
plank/laravel-mediable
src/MediaMover.php
MediaMover.removeExtensionFromFilename
protected function removeExtensionFromFilename($filename, $extension) { $extension = '.'.$extension; $extension_length = mb_strlen($filename) - mb_strlen($extension); if (mb_strrpos($filename, $extension) === $extension_length) { $filename = mb_substr($filename, 0, $extension_length); } return $filename; }
php
protected function removeExtensionFromFilename($filename, $extension) { $extension = '.'.$extension; $extension_length = mb_strlen($filename) - mb_strlen($extension); if (mb_strrpos($filename, $extension) === $extension_length) { $filename = mb_substr($filename, 0, $extension_length); } return $filename; }
[ "protected", "function", "removeExtensionFromFilename", "(", "$", "filename", ",", "$", "extension", ")", "{", "$", "extension", "=", "'.'", ".", "$", "extension", ";", "$", "extension_length", "=", "mb_strlen", "(", "$", "filename", ")", "-", "mb_strlen", "...
Remove the media's extension from a filename. @param string $filename @param string $extension @return string
[ "Remove", "the", "media", "s", "extension", "from", "a", "filename", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaMover.php#L116-L125
train
plank/laravel-mediable
src/Commands/ImportMediaCommand.php
ImportMediaCommand.listFiles
protected function listFiles($disk, $directory = '', $recursive = true) { if ($recursive) { return $this->filesystem->disk($disk)->allFiles($directory); } else { return $this->filesystem->disk($disk)->files($directory); } }
php
protected function listFiles($disk, $directory = '', $recursive = true) { if ($recursive) { return $this->filesystem->disk($disk)->allFiles($directory); } else { return $this->filesystem->disk($disk)->files($directory); } }
[ "protected", "function", "listFiles", "(", "$", "disk", ",", "$", "directory", "=", "''", ",", "$", "recursive", "=", "true", ")", "{", "if", "(", "$", "recursive", ")", "{", "return", "$", "this", "->", "filesystem", "->", "disk", "(", "$", "disk", ...
Generate a list of all files in the specified directory. @param string $disk @param string $directory @param bool $recursive @return array
[ "Generate", "a", "list", "of", "all", "files", "in", "the", "specified", "directory", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Commands/ImportMediaCommand.php#L105-L112
train
plank/laravel-mediable
src/Commands/ImportMediaCommand.php
ImportMediaCommand.getRecordForFile
protected function getRecordForFile($path, $existing_media) { $directory = File::cleanDirname($path); $filename = pathinfo($path, PATHINFO_FILENAME); $extension = pathinfo($path, PATHINFO_EXTENSION); return $existing_media->filter(function (Media $media) use ($directory, $filename, $extension) { return $media->directory == $directory && $media->filename == $filename && $media->extension == $extension; })->first(); }
php
protected function getRecordForFile($path, $existing_media) { $directory = File::cleanDirname($path); $filename = pathinfo($path, PATHINFO_FILENAME); $extension = pathinfo($path, PATHINFO_EXTENSION); return $existing_media->filter(function (Media $media) use ($directory, $filename, $extension) { return $media->directory == $directory && $media->filename == $filename && $media->extension == $extension; })->first(); }
[ "protected", "function", "getRecordForFile", "(", "$", "path", ",", "$", "existing_media", ")", "{", "$", "directory", "=", "File", "::", "cleanDirname", "(", "$", "path", ")", ";", "$", "filename", "=", "pathinfo", "(", "$", "path", ",", "PATHINFO_FILENAM...
Search through the record list for one matching the provided path. @param string $path @param \Illuminate\Database\Eloquent\Collection $existing_media @return \Plank\Mediable\Media|null
[ "Search", "through", "the", "record", "list", "for", "one", "matching", "the", "provided", "path", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Commands/ImportMediaCommand.php#L120-L129
train
plank/laravel-mediable
src/Commands/ImportMediaCommand.php
ImportMediaCommand.createRecordForFile
protected function createRecordForFile($disk, $path) { try { $this->uploader->importPath($disk, $path); ++$this->counters['created']; $this->info("Created Record for file at {$path}", 'v'); } catch (MediaUploadException $e) { $this->warn($e->getMessage(), 'vvv'); ++$this->counters['skipped']; $this->info("Skipped file at {$path}", 'v'); } }
php
protected function createRecordForFile($disk, $path) { try { $this->uploader->importPath($disk, $path); ++$this->counters['created']; $this->info("Created Record for file at {$path}", 'v'); } catch (MediaUploadException $e) { $this->warn($e->getMessage(), 'vvv'); ++$this->counters['skipped']; $this->info("Skipped file at {$path}", 'v'); } }
[ "protected", "function", "createRecordForFile", "(", "$", "disk", ",", "$", "path", ")", "{", "try", "{", "$", "this", "->", "uploader", "->", "importPath", "(", "$", "disk", ",", "$", "path", ")", ";", "++", "$", "this", "->", "counters", "[", "'cre...
Generate a new media record. @param string $disk @param string $path @return void
[ "Generate", "a", "new", "media", "record", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Commands/ImportMediaCommand.php#L137-L148
train
plank/laravel-mediable
src/Commands/ImportMediaCommand.php
ImportMediaCommand.updateRecordForFile
protected function updateRecordForFile(Media $media, $path) { try { if ($this->uploader->update($media)) { ++$this->counters['updated']; $this->info("Updated record for {$path}", 'v'); } else { ++$this->counters['skipped']; $this->info("Skipped unmodified file at {$path}", 'v'); } } catch (MediaUploadException $e) { $this->warn($e->getMessage(), 'vvv'); ++$this->counters['skipped']; $this->info("Skipped file at {$path}", 'v'); } }
php
protected function updateRecordForFile(Media $media, $path) { try { if ($this->uploader->update($media)) { ++$this->counters['updated']; $this->info("Updated record for {$path}", 'v'); } else { ++$this->counters['skipped']; $this->info("Skipped unmodified file at {$path}", 'v'); } } catch (MediaUploadException $e) { $this->warn($e->getMessage(), 'vvv'); ++$this->counters['skipped']; $this->info("Skipped file at {$path}", 'v'); } }
[ "protected", "function", "updateRecordForFile", "(", "Media", "$", "media", ",", "$", "path", ")", "{", "try", "{", "if", "(", "$", "this", "->", "uploader", "->", "update", "(", "$", "media", ")", ")", "{", "++", "$", "this", "->", "counters", "[", ...
Update an existing media record. @param \Plank\Mediable\Media $media @param string $path @return void
[ "Update", "an", "existing", "media", "record", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Commands/ImportMediaCommand.php#L156-L171
train
plank/laravel-mediable
src/Commands/ImportMediaCommand.php
ImportMediaCommand.outputCounters
protected function outputCounters($force) { $this->info(sprintf('Imported %d file(s).', $this->counters['created'])); if ($this->counters['updated'] > 0) { $this->info(sprintf('Updated %d record(s).', $this->counters['updated'])); } if ($this->counters['skipped'] > 0) { $this->info(sprintf('Skipped %d file(s).', $this->counters['skipped'])); } }
php
protected function outputCounters($force) { $this->info(sprintf('Imported %d file(s).', $this->counters['created'])); if ($this->counters['updated'] > 0) { $this->info(sprintf('Updated %d record(s).', $this->counters['updated'])); } if ($this->counters['skipped'] > 0) { $this->info(sprintf('Skipped %d file(s).', $this->counters['skipped'])); } }
[ "protected", "function", "outputCounters", "(", "$", "force", ")", "{", "$", "this", "->", "info", "(", "sprintf", "(", "'Imported %d file(s).'", ",", "$", "this", "->", "counters", "[", "'created'", "]", ")", ")", ";", "if", "(", "$", "this", "->", "c...
Send the counter total to the console. @param bool $force @return void
[ "Send", "the", "counter", "total", "to", "the", "console", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Commands/ImportMediaCommand.php#L178-L187
train
plank/laravel-mediable
src/Mediable.php
Mediable.scopeWhereHasMedia
public function scopeWhereHasMedia(Builder $q, $tags, $match_all = false) { if ($match_all && is_array($tags) && count($tags) > 1) { return $this->scopeWhereHasMediaMatchAll($q, $tags); } $q->whereHas('media', function (Builder $q) use ($tags) { $q->whereIn('tag', (array) $tags); }); }
php
public function scopeWhereHasMedia(Builder $q, $tags, $match_all = false) { if ($match_all && is_array($tags) && count($tags) > 1) { return $this->scopeWhereHasMediaMatchAll($q, $tags); } $q->whereHas('media', function (Builder $q) use ($tags) { $q->whereIn('tag', (array) $tags); }); }
[ "public", "function", "scopeWhereHasMedia", "(", "Builder", "$", "q", ",", "$", "tags", ",", "$", "match_all", "=", "false", ")", "{", "if", "(", "$", "match_all", "&&", "is_array", "(", "$", "tags", ")", "&&", "count", "(", "$", "tags", ")", ">", ...
Query scope to detect the presence of one or more attached media for a given tag. @param \Illuminate\Database\Eloquent\Builder $q @param string|string[] $tags @param bool $match_all @return void
[ "Query", "scope", "to", "detect", "the", "presence", "of", "one", "or", "more", "attached", "media", "for", "a", "given", "tag", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L63-L71
train
plank/laravel-mediable
src/Mediable.php
Mediable.scopeWhereHasMediaMatchAll
public function scopeWhereHasMediaMatchAll(Builder $q, array $tags) { $grammar = $q->getQuery()->getGrammar(); $subquery = $this->newMatchAllQuery($tags) ->selectRaw('count(*)') ->whereRaw($grammar->wrap($this->mediaQualifiedForeignKey()).' = '.$grammar->wrap($this->getQualifiedKeyName())); $q->whereRaw('('.$subquery->toSql().') >= 1', $subquery->getBindings()); }
php
public function scopeWhereHasMediaMatchAll(Builder $q, array $tags) { $grammar = $q->getQuery()->getGrammar(); $subquery = $this->newMatchAllQuery($tags) ->selectRaw('count(*)') ->whereRaw($grammar->wrap($this->mediaQualifiedForeignKey()).' = '.$grammar->wrap($this->getQualifiedKeyName())); $q->whereRaw('('.$subquery->toSql().') >= 1', $subquery->getBindings()); }
[ "public", "function", "scopeWhereHasMediaMatchAll", "(", "Builder", "$", "q", ",", "array", "$", "tags", ")", "{", "$", "grammar", "=", "$", "q", "->", "getQuery", "(", ")", "->", "getGrammar", "(", ")", ";", "$", "subquery", "=", "$", "this", "->", ...
Query scope to detect the presence of one or more attached media that is bound to all of the specified tags simultaneously. @param \Illuminate\Database\Eloquent\Builder $q @param string[] $tags @return void
[ "Query", "scope", "to", "detect", "the", "presence", "of", "one", "or", "more", "attached", "media", "that", "is", "bound", "to", "all", "of", "the", "specified", "tags", "simultaneously", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L79-L86
train
plank/laravel-mediable
src/Mediable.php
Mediable.scopeWithMedia
public function scopeWithMedia(Builder $q, $tags = [], $match_all = false) { $tags = (array) $tags; if (empty($tags)) { return $q->with('media'); } if ($match_all) { return $q->withMediaMatchAll($tags); } $q->with(['media' => function (MorphToMany $q) use ($tags) { $this->wherePivotTagIn($q, $tags); }]); }
php
public function scopeWithMedia(Builder $q, $tags = [], $match_all = false) { $tags = (array) $tags; if (empty($tags)) { return $q->with('media'); } if ($match_all) { return $q->withMediaMatchAll($tags); } $q->with(['media' => function (MorphToMany $q) use ($tags) { $this->wherePivotTagIn($q, $tags); }]); }
[ "public", "function", "scopeWithMedia", "(", "Builder", "$", "q", ",", "$", "tags", "=", "[", "]", ",", "$", "match_all", "=", "false", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "tags", ";", "if", "(", "empty", "(", "$", "tags", ")", ...
Query scope to eager load attached media. @param \Illuminate\Database\Eloquent\Builder $q @param string|string[] $tags If one or more tags are specified, only media attached to those tags will be loaded. @param bool $match_all Only load media matching all provided tags @return void
[ "Query", "scope", "to", "eager", "load", "attached", "media", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L96-L111
train
plank/laravel-mediable
src/Mediable.php
Mediable.scopeWithMediaMatchAll
public function scopeWithMediaMatchAll(Builder $q, $tags = []) { $tags = (array) $tags; $q->with(['media' => function (MorphToMany $q) use ($tags) { $this->addMatchAllToEagerLoadQuery($q, $tags); }]); }
php
public function scopeWithMediaMatchAll(Builder $q, $tags = []) { $tags = (array) $tags; $q->with(['media' => function (MorphToMany $q) use ($tags) { $this->addMatchAllToEagerLoadQuery($q, $tags); }]); }
[ "public", "function", "scopeWithMediaMatchAll", "(", "Builder", "$", "q", ",", "$", "tags", "=", "[", "]", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "tags", ";", "$", "q", "->", "with", "(", "[", "'media'", "=>", "function", "(", "MorphTo...
Query scope to eager load attached media assigned to multiple tags. @param \Illuminate\Database\Eloquent\Builder $q @param string|string[] $tags @return void
[ "Query", "scope", "to", "eager", "load", "attached", "media", "assigned", "to", "multiple", "tags", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L119-L125
train
plank/laravel-mediable
src/Mediable.php
Mediable.loadMedia
public function loadMedia($tags = [], $match_all = false) { $tags = (array) $tags; if (empty($tags)) { return $this->load('media'); } if ($match_all) { return $this->loadMediaMatchAll($tags); } $this->load(['media' => function (MorphToMany $q) use ($tags) { $this->wherePivotTagIn($q, $tags); }]); return $this; }
php
public function loadMedia($tags = [], $match_all = false) { $tags = (array) $tags; if (empty($tags)) { return $this->load('media'); } if ($match_all) { return $this->loadMediaMatchAll($tags); } $this->load(['media' => function (MorphToMany $q) use ($tags) { $this->wherePivotTagIn($q, $tags); }]); return $this; }
[ "public", "function", "loadMedia", "(", "$", "tags", "=", "[", "]", ",", "$", "match_all", "=", "false", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "tags", ";", "if", "(", "empty", "(", "$", "tags", ")", ")", "{", "return", "$", "this"...
Lazy eager load attached media relationships. @param string|string[] $tags If one or more tags are specified, only media attached to those tags will be loaded. @param bool $match_all Only load media matching all provided tags @return $this
[ "Lazy", "eager", "load", "attached", "media", "relationships", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L133-L150
train
plank/laravel-mediable
src/Mediable.php
Mediable.loadMediaMatchAll
public function loadMediaMatchAll($tags = []) { $tags = (array) $tags; $this->load(['media' => function (MorphToMany $q) use ($tags) { $this->addMatchAllToEagerLoadQuery($q, $tags); }]); return $this; }
php
public function loadMediaMatchAll($tags = []) { $tags = (array) $tags; $this->load(['media' => function (MorphToMany $q) use ($tags) { $this->addMatchAllToEagerLoadQuery($q, $tags); }]); return $this; }
[ "public", "function", "loadMediaMatchAll", "(", "$", "tags", "=", "[", "]", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "tags", ";", "$", "this", "->", "load", "(", "[", "'media'", "=>", "function", "(", "MorphToMany", "$", "q", ")", "use",...
Lazy eager load attached media relationships matching all provided tags. @param string|string[] $tags one or more tags @return $this
[ "Lazy", "eager", "load", "attached", "media", "relationships", "matching", "all", "provided", "tags", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L157-L165
train
plank/laravel-mediable
src/Mediable.php
Mediable.attachMedia
public function attachMedia($media, $tags) { $tags = (array) $tags; $increments = $this->getOrderValueForTags($tags); $ids = $this->extractIds($media); foreach ($tags as $tag) { $attach = []; foreach ($ids as $id) { $attach[$id] = [ 'tag' => $tag, 'order' => ++$increments[$tag], ]; } $this->media()->attach($attach); } $this->markMediaDirty($tags); }
php
public function attachMedia($media, $tags) { $tags = (array) $tags; $increments = $this->getOrderValueForTags($tags); $ids = $this->extractIds($media); foreach ($tags as $tag) { $attach = []; foreach ($ids as $id) { $attach[$id] = [ 'tag' => $tag, 'order' => ++$increments[$tag], ]; } $this->media()->attach($attach); } $this->markMediaDirty($tags); }
[ "public", "function", "attachMedia", "(", "$", "media", ",", "$", "tags", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "tags", ";", "$", "increments", "=", "$", "this", "->", "getOrderValueForTags", "(", "$", "tags", ")", ";", "$", "ids", "=...
Attach a media entity to the model with one or more tags. @param mixed $media Either a string or numeric id, an array of ids, an instance of `Media` or an instance of `\Illuminate\Database\Eloquent\Collection` @param string|string[] $tags One or more tags to define the relation @return void
[ "Attach", "a", "media", "entity", "to", "the", "model", "with", "one", "or", "more", "tags", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L173-L192
train
plank/laravel-mediable
src/Mediable.php
Mediable.detachMedia
public function detachMedia($media, $tags = null) { $query = $this->media(); if ($tags) { $query->wherePivotIn('tag', (array) $tags); } $query->detach($media); $this->markMediaDirty($tags); }
php
public function detachMedia($media, $tags = null) { $query = $this->media(); if ($tags) { $query->wherePivotIn('tag', (array) $tags); } $query->detach($media); $this->markMediaDirty($tags); }
[ "public", "function", "detachMedia", "(", "$", "media", ",", "$", "tags", "=", "null", ")", "{", "$", "query", "=", "$", "this", "->", "media", "(", ")", ";", "if", "(", "$", "tags", ")", "{", "$", "query", "->", "wherePivotIn", "(", "'tag'", ","...
Detach a media item from the model. @param mixed $media @param string|string[]|null $tags If provided, will remove the media from the model for the provided tag(s) only If omitted, will remove the media from the media for all tags @return void
[ "Detach", "a", "media", "item", "from", "the", "model", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L214-L222
train
plank/laravel-mediable
src/Mediable.php
Mediable.detachMediaTags
public function detachMediaTags($tags) { $this->media()->newPivotStatement() ->where($this->media()->getMorphType(), $this->media()->getMorphClass()) ->where($this->mediaQualifiedForeignKey(), $this->getKey()) ->whereIn('tag', (array) $tags)->delete(); $this->markMediaDirty($tags); }
php
public function detachMediaTags($tags) { $this->media()->newPivotStatement() ->where($this->media()->getMorphType(), $this->media()->getMorphClass()) ->where($this->mediaQualifiedForeignKey(), $this->getKey()) ->whereIn('tag', (array) $tags)->delete(); $this->markMediaDirty($tags); }
[ "public", "function", "detachMediaTags", "(", "$", "tags", ")", "{", "$", "this", "->", "media", "(", ")", "->", "newPivotStatement", "(", ")", "->", "where", "(", "$", "this", "->", "media", "(", ")", "->", "getMorphType", "(", ")", ",", "$", "this"...
Remove one or more tags from the model, detaching any media using those tags. @param string|string[] $tags @return void
[ "Remove", "one", "or", "more", "tags", "from", "the", "model", "detaching", "any", "media", "using", "those", "tags", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L229-L236
train
plank/laravel-mediable
src/Mediable.php
Mediable.getMedia
public function getMedia($tags, $match_all = false) { if ($match_all) { return $this->getMediaMatchAll($tags); } $this->rehydrateMediaIfNecessary($tags); return $this->media //exclude media not matching at least one tag ->filter(function (Media $media) use ($tags) { return in_array($media->pivot->tag, (array) $tags); }) //remove duplicate media ->keyBy(function (Media $media) { return $media->getKey(); })->values(); }
php
public function getMedia($tags, $match_all = false) { if ($match_all) { return $this->getMediaMatchAll($tags); } $this->rehydrateMediaIfNecessary($tags); return $this->media //exclude media not matching at least one tag ->filter(function (Media $media) use ($tags) { return in_array($media->pivot->tag, (array) $tags); }) //remove duplicate media ->keyBy(function (Media $media) { return $media->getKey(); })->values(); }
[ "public", "function", "getMedia", "(", "$", "tags", ",", "$", "match_all", "=", "false", ")", "{", "if", "(", "$", "match_all", ")", "{", "return", "$", "this", "->", "getMediaMatchAll", "(", "$", "tags", ")", ";", "}", "$", "this", "->", "rehydrateM...
Retrieve media attached to the model. @param string|string[] $tags @param bool $match_all If false, will return media attached to any of the provided tags If true, will return media attached to all of the provided tags simultaneously @return \Illuminate\Database\Eloquent\Collection|\Plank\Mediable\Media[]
[ "Retrieve", "media", "attached", "to", "the", "model", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L259-L276
train
plank/laravel-mediable
src/Mediable.php
Mediable.getMediaMatchAll
public function getMediaMatchAll(array $tags) { $this->rehydrateMediaIfNecessary($tags); //group all tags for each media $model_tags = $this->media->reduce(function ($carry, Media $media) { $carry[$media->getKey()][] = $media->pivot->tag; return $carry; }, []); //exclude media not matching all tags return $this->media->filter(function (Media $media) use ($tags, $model_tags) { return count(array_intersect($tags, $model_tags[$media->getKey()])) === count($tags); }) //remove duplicate media ->keyBy(function (Media $media) { return $media->getKey(); })->values(); }
php
public function getMediaMatchAll(array $tags) { $this->rehydrateMediaIfNecessary($tags); //group all tags for each media $model_tags = $this->media->reduce(function ($carry, Media $media) { $carry[$media->getKey()][] = $media->pivot->tag; return $carry; }, []); //exclude media not matching all tags return $this->media->filter(function (Media $media) use ($tags, $model_tags) { return count(array_intersect($tags, $model_tags[$media->getKey()])) === count($tags); }) //remove duplicate media ->keyBy(function (Media $media) { return $media->getKey(); })->values(); }
[ "public", "function", "getMediaMatchAll", "(", "array", "$", "tags", ")", "{", "$", "this", "->", "rehydrateMediaIfNecessary", "(", "$", "tags", ")", ";", "//group all tags for each media", "$", "model_tags", "=", "$", "this", "->", "media", "->", "reduce", "(...
Retrieve media attached to multiple tags simultaneously. @param string[] $tags @return \Illuminate\Database\Eloquent\Collection|\Plank\Mediable\Media[]
[ "Retrieve", "media", "attached", "to", "multiple", "tags", "simultaneously", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L283-L302
train
plank/laravel-mediable
src/Mediable.php
Mediable.getTagsForMedia
public function getTagsForMedia(Media $media) { $this->rehydrateMediaIfNecessary(); return $this->media->reduce(function ($carry, Media $item) use ($media) { if ($item->getKey() === $media->getKey()) { $carry[] = $item->pivot->tag; } return $carry; }, []); }
php
public function getTagsForMedia(Media $media) { $this->rehydrateMediaIfNecessary(); return $this->media->reduce(function ($carry, Media $item) use ($media) { if ($item->getKey() === $media->getKey()) { $carry[] = $item->pivot->tag; } return $carry; }, []); }
[ "public", "function", "getTagsForMedia", "(", "Media", "$", "media", ")", "{", "$", "this", "->", "rehydrateMediaIfNecessary", "(", ")", ";", "return", "$", "this", "->", "media", "->", "reduce", "(", "function", "(", "$", "carry", ",", "Media", "$", "it...
Get a list of all tags that the media is attached to. @param \Plank\Mediable\Media $media @return string[]
[ "Get", "a", "list", "of", "all", "tags", "that", "the", "media", "is", "attached", "to", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L344-L355
train
plank/laravel-mediable
src/Mediable.php
Mediable.mediaIsDirty
protected function mediaIsDirty($tags = null) { if (is_null($tags)) { return count($this->media_dirty_tags); } else { return count(array_intersect((array) $tags, $this->media_dirty_tags)); } }
php
protected function mediaIsDirty($tags = null) { if (is_null($tags)) { return count($this->media_dirty_tags); } else { return count(array_intersect((array) $tags, $this->media_dirty_tags)); } }
[ "protected", "function", "mediaIsDirty", "(", "$", "tags", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "tags", ")", ")", "{", "return", "count", "(", "$", "this", "->", "media_dirty_tags", ")", ";", "}", "else", "{", "return", "count", "("...
Check if media attached to the specified tags has been modified. @param null|string|string[] $tags If omitted, will return `true` if any tags have been modified @return bool
[ "Check", "if", "media", "attached", "to", "the", "specified", "tags", "has", "been", "modified", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L375-L382
train
plank/laravel-mediable
src/Mediable.php
Mediable.rehydrateMediaIfNecessary
protected function rehydrateMediaIfNecessary($tags = null) { if ($this->rehydratesMedia() && $this->mediaIsDirty($tags)) { $this->loadMedia(); } }
php
protected function rehydrateMediaIfNecessary($tags = null) { if ($this->rehydratesMedia() && $this->mediaIsDirty($tags)) { $this->loadMedia(); } }
[ "protected", "function", "rehydrateMediaIfNecessary", "(", "$", "tags", "=", "null", ")", "{", "if", "(", "$", "this", "->", "rehydratesMedia", "(", ")", "&&", "$", "this", "->", "mediaIsDirty", "(", "$", "tags", ")", ")", "{", "$", "this", "->", "load...
Reloads media relationship if allowed and necessary. @param null|string|string[] $tags @return void
[ "Reloads", "media", "relationship", "if", "allowed", "and", "necessary", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L389-L394
train
plank/laravel-mediable
src/Mediable.php
Mediable.newMatchAllQuery
protected function newMatchAllQuery($tags = []) { $tags = (array) $tags; $grammar = $this->media()->getBaseQuery()->getGrammar(); return $this->media()->newPivotStatement() ->where($this->media()->getMorphType(), $this->media()->getMorphClass()) ->whereIn('tag', $tags) ->groupBy($this->mediaQualifiedRelatedKey()) ->havingRaw('count('.$grammar->wrap($this->mediaQualifiedRelatedKey()).') = '.count($tags)); }
php
protected function newMatchAllQuery($tags = []) { $tags = (array) $tags; $grammar = $this->media()->getBaseQuery()->getGrammar(); return $this->media()->newPivotStatement() ->where($this->media()->getMorphType(), $this->media()->getMorphClass()) ->whereIn('tag', $tags) ->groupBy($this->mediaQualifiedRelatedKey()) ->havingRaw('count('.$grammar->wrap($this->mediaQualifiedRelatedKey()).') = '.count($tags)); }
[ "protected", "function", "newMatchAllQuery", "(", "$", "tags", "=", "[", "]", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "tags", ";", "$", "grammar", "=", "$", "this", "->", "media", "(", ")", "->", "getBaseQuery", "(", ")", "->", "getGram...
Generate a query builder for. @param string|string[] $tags @return \Illuminate\Database\Query\Builder
[ "Generate", "a", "query", "builder", "for", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L416-L425
train
plank/laravel-mediable
src/Mediable.php
Mediable.addMatchAllToEagerLoadQuery
protected function addMatchAllToEagerLoadQuery(MorphToMany $q, $tags = []) { $tags = (array) $tags; $grammar = $q->getBaseQuery()->getGrammar(); $subquery = $this->newMatchAllQuery($tags)->select($this->mediaQualifiedRelatedKey()); $q->whereRaw($grammar->wrap($this->mediaQualifiedRelatedKey()).' IN ('.$subquery->toSql().')', $subquery->getBindings()); $this->wherePivotTagIn($q, $tags); }
php
protected function addMatchAllToEagerLoadQuery(MorphToMany $q, $tags = []) { $tags = (array) $tags; $grammar = $q->getBaseQuery()->getGrammar(); $subquery = $this->newMatchAllQuery($tags)->select($this->mediaQualifiedRelatedKey()); $q->whereRaw($grammar->wrap($this->mediaQualifiedRelatedKey()).' IN ('.$subquery->toSql().')', $subquery->getBindings()); $this->wherePivotTagIn($q, $tags); }
[ "protected", "function", "addMatchAllToEagerLoadQuery", "(", "MorphToMany", "$", "q", ",", "$", "tags", "=", "[", "]", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "tags", ";", "$", "grammar", "=", "$", "q", "->", "getBaseQuery", "(", ")", "->...
Modify an eager load query to only load media assigned to all provided tags simultaneously. @param \Illuminate\Database\Eloquent\Relations\MorphToMany $q @param string|string[] $tags @return void
[ "Modify", "an", "eager", "load", "query", "to", "only", "load", "media", "assigned", "to", "all", "provided", "tags", "simultaneously", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L433-L440
train
plank/laravel-mediable
src/Mediable.php
Mediable.handleMediableDeletion
protected function handleMediableDeletion() { // only cascade soft deletes when configured if (static::hasGlobalScope(SoftDeletingScope::class) && ! $this->forceDeleting) { if (config('mediable.detach_on_soft_delete')) { $this->media()->detach(); } // always cascade for hard deletes } else { $this->media()->detach(); } }
php
protected function handleMediableDeletion() { // only cascade soft deletes when configured if (static::hasGlobalScope(SoftDeletingScope::class) && ! $this->forceDeleting) { if (config('mediable.detach_on_soft_delete')) { $this->media()->detach(); } // always cascade for hard deletes } else { $this->media()->detach(); } }
[ "protected", "function", "handleMediableDeletion", "(", ")", "{", "// only cascade soft deletes when configured", "if", "(", "static", "::", "hasGlobalScope", "(", "SoftDeletingScope", "::", "class", ")", "&&", "!", "$", "this", "->", "forceDeleting", ")", "{", "if"...
Determine whether media relationships should be detached when the model is deleted or soft deleted. @return void
[ "Determine", "whether", "media", "relationships", "should", "be", "detached", "when", "the", "model", "is", "deleted", "or", "soft", "deleted", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L446-L457
train
plank/laravel-mediable
src/Mediable.php
Mediable.getOrderValueForTags
private function getOrderValueForTags($tags) { $q = $this->media()->newPivotStatement(); $tags = array_map('strval', (array) $tags); $grammar = $q->getGrammar(); $result = $q->selectRaw($grammar->wrap('tag').', max('.$grammar->wrap('order').') as aggregate') ->where('mediable_type', $this->getMorphClass()) ->where('mediable_id', $this->getKey()) ->whereIn('tag', $tags) ->groupBy('tag') ->pluck('aggregate', 'tag'); $empty = array_combine($tags, array_fill(0, count($tags), 0)); $merged = collect($result)->toArray() + $empty; return $merged; }
php
private function getOrderValueForTags($tags) { $q = $this->media()->newPivotStatement(); $tags = array_map('strval', (array) $tags); $grammar = $q->getGrammar(); $result = $q->selectRaw($grammar->wrap('tag').', max('.$grammar->wrap('order').') as aggregate') ->where('mediable_type', $this->getMorphClass()) ->where('mediable_id', $this->getKey()) ->whereIn('tag', $tags) ->groupBy('tag') ->pluck('aggregate', 'tag'); $empty = array_combine($tags, array_fill(0, count($tags), 0)); $merged = collect($result)->toArray() + $empty; return $merged; }
[ "private", "function", "getOrderValueForTags", "(", "$", "tags", ")", "{", "$", "q", "=", "$", "this", "->", "media", "(", ")", "->", "newPivotStatement", "(", ")", ";", "$", "tags", "=", "array_map", "(", "'strval'", ",", "(", "array", ")", "$", "ta...
Determine the highest order value assigned to each provided tag. @param string|string[] $tags @return array
[ "Determine", "the", "highest", "order", "value", "assigned", "to", "each", "provided", "tag", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L464-L481
train
plank/laravel-mediable
src/Mediable.php
Mediable.extractIds
private function extractIds($input) { if ($input instanceof Collection) { return $input->modelKeys(); } if ($input instanceof Media) { return [$input->getKey()]; } return (array) $input; }
php
private function extractIds($input) { if ($input instanceof Collection) { return $input->modelKeys(); } if ($input instanceof Media) { return [$input->getKey()]; } return (array) $input; }
[ "private", "function", "extractIds", "(", "$", "input", ")", "{", "if", "(", "$", "input", "instanceof", "Collection", ")", "{", "return", "$", "input", "->", "modelKeys", "(", ")", ";", "}", "if", "(", "$", "input", "instanceof", "Media", ")", "{", ...
Convert mixed input to array of ids. @param mixed $input @return array
[ "Convert", "mixed", "input", "to", "array", "of", "ids", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L488-L499
train
plank/laravel-mediable
src/Mediable.php
Mediable.mediaQualifiedForeignKey
private function mediaQualifiedForeignKey() { $relation = $this->media(); if (method_exists($relation, 'getQualifiedForeignPivotKeyName')) { return $relation->getQualifiedForeignPivotKeyName(); } elseif (method_exists($relation, 'getQualifiedForeignKeyName')) { return $relation->getQualifiedForeignKeyName(); } return $relation->getForeignKey(); }
php
private function mediaQualifiedForeignKey() { $relation = $this->media(); if (method_exists($relation, 'getQualifiedForeignPivotKeyName')) { return $relation->getQualifiedForeignPivotKeyName(); } elseif (method_exists($relation, 'getQualifiedForeignKeyName')) { return $relation->getQualifiedForeignKeyName(); } return $relation->getForeignKey(); }
[ "private", "function", "mediaQualifiedForeignKey", "(", ")", "{", "$", "relation", "=", "$", "this", "->", "media", "(", ")", ";", "if", "(", "method_exists", "(", "$", "relation", ",", "'getQualifiedForeignPivotKeyName'", ")", ")", "{", "return", "$", "rela...
Key the name of the foreign key field of the media relation Accounts for the change of method name in Laravel 5.4 @return string
[ "Key", "the", "name", "of", "the", "foreign", "key", "field", "of", "the", "media", "relation" ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L533-L542
train
plank/laravel-mediable
src/Mediable.php
Mediable.mediaQualifiedRelatedKey
private function mediaQualifiedRelatedKey() { $relation = $this->media(); // Laravel 5.5 if (method_exists($relation, 'getQualifiedRelatedPivotKeyName')) { return $relation->getQualifiedRelatedPivotKeyName(); // Laravel 5.4 } elseif (method_exists($relation, 'getQualifiedRelatedKeyName')) { return $relation->getQualifiedRelatedKeyName(); } // Laravel <= 5.3 return $relation->getOtherKey(); }
php
private function mediaQualifiedRelatedKey() { $relation = $this->media(); // Laravel 5.5 if (method_exists($relation, 'getQualifiedRelatedPivotKeyName')) { return $relation->getQualifiedRelatedPivotKeyName(); // Laravel 5.4 } elseif (method_exists($relation, 'getQualifiedRelatedKeyName')) { return $relation->getQualifiedRelatedKeyName(); } // Laravel <= 5.3 return $relation->getOtherKey(); }
[ "private", "function", "mediaQualifiedRelatedKey", "(", ")", "{", "$", "relation", "=", "$", "this", "->", "media", "(", ")", ";", "// Laravel 5.5", "if", "(", "method_exists", "(", "$", "relation", ",", "'getQualifiedRelatedPivotKeyName'", ")", ")", "{", "ret...
Key the name of the related key field of the media relation Accounts for the change of method name in Laravel 5.4 and again in Laravel 5.5 @return string
[ "Key", "the", "name", "of", "the", "related", "key", "field", "of", "the", "media", "relation" ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L551-L563
train
plank/laravel-mediable
src/Mediable.php
Mediable.wherePivotTagIn
private function wherePivotTagIn(MorphToMany $q, $tags = []) { method_exists($q, 'wherePivotIn') ? $q->wherePivotIn('tag', $tags) : $q->whereIn($this->media()->getTable().'.tag', $tags); }
php
private function wherePivotTagIn(MorphToMany $q, $tags = []) { method_exists($q, 'wherePivotIn') ? $q->wherePivotIn('tag', $tags) : $q->whereIn($this->media()->getTable().'.tag', $tags); }
[ "private", "function", "wherePivotTagIn", "(", "MorphToMany", "$", "q", ",", "$", "tags", "=", "[", "]", ")", "{", "method_exists", "(", "$", "q", ",", "'wherePivotIn'", ")", "?", "$", "q", "->", "wherePivotIn", "(", "'tag'", ",", "$", "tags", ")", "...
perform a WHERE IN on the pivot table's tags column Adds support for Laravel <= 5.2, which does not provide a `wherePivotIn()` method @param \Illuminate\Database\Eloquent\Relations\MorphToMany $q @param string|string[] $tags @return void
[ "perform", "a", "WHERE", "IN", "on", "the", "pivot", "table", "s", "tags", "column" ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Mediable.php#L573-L576
train
plank/laravel-mediable
src/Media.php
Media.scopeInDirectory
public function scopeInDirectory(Builder $q, $disk, $directory, $recursive = false) { $q->where('disk', $disk); if ($recursive) { $directory = str_replace(['%', '_'], ['\%', '\_'], $directory); $q->where('directory', 'like', $directory.'%'); } else { $q->where('directory', '=', $directory); } }
php
public function scopeInDirectory(Builder $q, $disk, $directory, $recursive = false) { $q->where('disk', $disk); if ($recursive) { $directory = str_replace(['%', '_'], ['\%', '\_'], $directory); $q->where('directory', 'like', $directory.'%'); } else { $q->where('directory', '=', $directory); } }
[ "public", "function", "scopeInDirectory", "(", "Builder", "$", "q", ",", "$", "disk", ",", "$", "directory", ",", "$", "recursive", "=", "false", ")", "{", "$", "q", "->", "where", "(", "'disk'", ",", "$", "disk", ")", ";", "if", "(", "$", "recursi...
Query scope for to find media in a particular directory. @param \Illuminate\Database\Eloquent\Builder $q @param string $disk Filesystem disk to search in @param string $directory Path relative to disk @param bool $recursive (_optional_) If true, will find media in or under the specified directory @return void
[ "Query", "scope", "for", "to", "find", "media", "in", "a", "particular", "directory", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Media.php#L91-L100
train
plank/laravel-mediable
src/Media.php
Media.scopeInOrUnderDirectory
public function scopeInOrUnderDirectory(Builder $q, $disk, $directory) { $q->inDirectory($disk, $directory, true); }
php
public function scopeInOrUnderDirectory(Builder $q, $disk, $directory) { $q->inDirectory($disk, $directory, true); }
[ "public", "function", "scopeInOrUnderDirectory", "(", "Builder", "$", "q", ",", "$", "disk", ",", "$", "directory", ")", "{", "$", "q", "->", "inDirectory", "(", "$", "disk", ",", "$", "directory", ",", "true", ")", ";", "}" ]
Query scope for finding media in a particular directory or one of its subdirectories. @param \Illuminate\Database\Eloquent\Builder $q @param string $disk Filesystem disk to search in @param string $directory Path relative to disk @return void
[ "Query", "scope", "for", "finding", "media", "in", "a", "particular", "directory", "or", "one", "of", "its", "subdirectories", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Media.php#L109-L112
train
plank/laravel-mediable
src/Media.php
Media.scopeWhereBasename
public function scopeWhereBasename(Builder $q, $basename) { $q->where('filename', pathinfo($basename, PATHINFO_FILENAME)) ->where('extension', pathinfo($basename, PATHINFO_EXTENSION)); }
php
public function scopeWhereBasename(Builder $q, $basename) { $q->where('filename', pathinfo($basename, PATHINFO_FILENAME)) ->where('extension', pathinfo($basename, PATHINFO_EXTENSION)); }
[ "public", "function", "scopeWhereBasename", "(", "Builder", "$", "q", ",", "$", "basename", ")", "{", "$", "q", "->", "where", "(", "'filename'", ",", "pathinfo", "(", "$", "basename", ",", "PATHINFO_FILENAME", ")", ")", "->", "where", "(", "'extension'", ...
Query scope for finding media by basename. @param \Illuminate\Database\Eloquent\Builder $q @param string $basename filename and extension @return void
[ "Query", "scope", "for", "finding", "media", "by", "basename", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Media.php#L120-L124
train
plank/laravel-mediable
src/Media.php
Media.scopeForPathOnDisk
public function scopeForPathOnDisk(Builder $q, $disk, $path) { $q->where('disk', $disk) ->where('directory', File::cleanDirname($path)) ->where('filename', pathinfo($path, PATHINFO_FILENAME)) ->where('extension', pathinfo($path, PATHINFO_EXTENSION)); }
php
public function scopeForPathOnDisk(Builder $q, $disk, $path) { $q->where('disk', $disk) ->where('directory', File::cleanDirname($path)) ->where('filename', pathinfo($path, PATHINFO_FILENAME)) ->where('extension', pathinfo($path, PATHINFO_EXTENSION)); }
[ "public", "function", "scopeForPathOnDisk", "(", "Builder", "$", "q", ",", "$", "disk", ",", "$", "path", ")", "{", "$", "q", "->", "where", "(", "'disk'", ",", "$", "disk", ")", "->", "where", "(", "'directory'", ",", "File", "::", "cleanDirname", "...
Query scope finding media at a path relative to a disk. @param \Illuminate\Database\Eloquent\Builder $q @param string $disk @param string $path directory, filename and extension @return void
[ "Query", "scope", "finding", "media", "at", "a", "path", "relative", "to", "a", "disk", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Media.php#L133-L139
train
plank/laravel-mediable
src/Media.php
Media.scopeUnordered
public function scopeUnordered(Builder $q) { $query = $q->getQuery(); if ($query->orders) { $query->orders = null; } }
php
public function scopeUnordered(Builder $q) { $query = $q->getQuery(); if ($query->orders) { $query->orders = null; } }
[ "public", "function", "scopeUnordered", "(", "Builder", "$", "q", ")", "{", "$", "query", "=", "$", "q", "->", "getQuery", "(", ")", ";", "if", "(", "$", "query", "->", "orders", ")", "{", "$", "query", "->", "orders", "=", "null", ";", "}", "}" ...
Query scope to remove the order by clause from the query. @param \Illuminate\Database\Eloquent\Builder $q @return void
[ "Query", "scope", "to", "remove", "the", "order", "by", "clause", "from", "the", "query", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/Media.php#L146-L152
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.toDirectory
public function toDirectory($directory) { $this->directory = trim($this->sanitizePath($directory), DIRECTORY_SEPARATOR); return $this; }
php
public function toDirectory($directory) { $this->directory = trim($this->sanitizePath($directory), DIRECTORY_SEPARATOR); return $this; }
[ "public", "function", "toDirectory", "(", "$", "directory", ")", "{", "$", "this", "->", "directory", "=", "trim", "(", "$", "this", "->", "sanitizePath", "(", "$", "directory", ")", ",", "DIRECTORY_SEPARATOR", ")", ";", "return", "$", "this", ";", "}" ]
Set the directory relative to the filesystem disk at which the file will be saved. @param string $directory @return static
[ "Set", "the", "directory", "relative", "to", "the", "filesystem", "disk", "at", "which", "the", "file", "will", "be", "saved", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L158-L163
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.useFilename
public function useFilename($filename) { $this->filename = $this->sanitizeFilename($filename); $this->hash_filename = false; return $this; }
php
public function useFilename($filename) { $this->filename = $this->sanitizeFilename($filename); $this->hash_filename = false; return $this; }
[ "public", "function", "useFilename", "(", "$", "filename", ")", "{", "$", "this", "->", "filename", "=", "$", "this", "->", "sanitizeFilename", "(", "$", "filename", ")", ";", "$", "this", "->", "hash_filename", "=", "false", ";", "return", "$", "this", ...
Specify the filename to copy to the file to. @param string $filename @return static
[ "Specify", "the", "filename", "to", "copy", "to", "the", "file", "to", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L170-L176
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.setTypeDefinition
public function setTypeDefinition($type, $mime_types, $extensions) { $this->config['aggregate_types'][$type] = [ 'mime_types' => (array) $mime_types, 'extensions' => (array) $extensions, ]; return $this; }
php
public function setTypeDefinition($type, $mime_types, $extensions) { $this->config['aggregate_types'][$type] = [ 'mime_types' => (array) $mime_types, 'extensions' => (array) $extensions, ]; return $this; }
[ "public", "function", "setTypeDefinition", "(", "$", "type", ",", "$", "mime_types", ",", "$", "extensions", ")", "{", "$", "this", "->", "config", "[", "'aggregate_types'", "]", "[", "$", "type", "]", "=", "[", "'mime_types'", "=>", "(", "array", ")", ...
Add or update the definition of a aggregate type. @param string $type the name of the type @param string|string[] $mime_types list of MIME types recognized @param string|string[] $extensions list of file extensions recognized @return static
[ "Add", "or", "update", "the", "definition", "of", "a", "aggregate", "type", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L323-L331
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.inferAggregateType
public function inferAggregateType($mime_type, $extension) { $allowed_types = $this->config['allowed_aggregate_types']; $types_for_mime = $this->possibleAggregateTypesForMimeType($mime_type); $types_for_extension = $this->possibleAggregateTypesForExtension($extension); if (count($allowed_types)) { $intersection = array_intersect($types_for_mime, $types_for_extension, $allowed_types); } else { $intersection = array_intersect($types_for_mime, $types_for_extension); } if (count($intersection)) { $type = $intersection[0]; } elseif (empty($types_for_mime) && empty($types_for_extension)) { if (! $this->config['allow_unrecognized_types']) { throw FileNotSupportedException::unrecognizedFileType($mime_type, $extension); } $type = Media::TYPE_OTHER; } else { if ($this->config['strict_type_checking']) { throw FileNotSupportedException::strictTypeMismatch($mime_type, $extension); } $merged = array_merge($types_for_mime, $types_for_extension); $type = reset($merged); } if (count($allowed_types) && ! in_array($type, $allowed_types)) { throw FileNotSupportedException::aggregateTypeRestricted($type, $allowed_types); } return $type; }
php
public function inferAggregateType($mime_type, $extension) { $allowed_types = $this->config['allowed_aggregate_types']; $types_for_mime = $this->possibleAggregateTypesForMimeType($mime_type); $types_for_extension = $this->possibleAggregateTypesForExtension($extension); if (count($allowed_types)) { $intersection = array_intersect($types_for_mime, $types_for_extension, $allowed_types); } else { $intersection = array_intersect($types_for_mime, $types_for_extension); } if (count($intersection)) { $type = $intersection[0]; } elseif (empty($types_for_mime) && empty($types_for_extension)) { if (! $this->config['allow_unrecognized_types']) { throw FileNotSupportedException::unrecognizedFileType($mime_type, $extension); } $type = Media::TYPE_OTHER; } else { if ($this->config['strict_type_checking']) { throw FileNotSupportedException::strictTypeMismatch($mime_type, $extension); } $merged = array_merge($types_for_mime, $types_for_extension); $type = reset($merged); } if (count($allowed_types) && ! in_array($type, $allowed_types)) { throw FileNotSupportedException::aggregateTypeRestricted($type, $allowed_types); } return $type; }
[ "public", "function", "inferAggregateType", "(", "$", "mime_type", ",", "$", "extension", ")", "{", "$", "allowed_types", "=", "$", "this", "->", "config", "[", "'allowed_aggregate_types'", "]", ";", "$", "types_for_mime", "=", "$", "this", "->", "possibleAggr...
Determine the aggregate type of the file based on the MIME type and the extension. @param string $mime_type @param string $extension @return string @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotSupportedException If the file type is not recognized @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotSupportedException If the file type is restricted @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotSupportedException If the aggregate type is restricted
[ "Determine", "the", "aggregate", "type", "of", "the", "file", "based", "on", "the", "MIME", "type", "and", "the", "extension", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L378-L410
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.possibleAggregateTypesForMimeType
public function possibleAggregateTypesForMimeType($mime) { $types = []; foreach ($this->config['aggregate_types'] as $type => $attributes) { if (in_array($mime, $attributes['mime_types'])) { $types[] = $type; } } return $types; }
php
public function possibleAggregateTypesForMimeType($mime) { $types = []; foreach ($this->config['aggregate_types'] as $type => $attributes) { if (in_array($mime, $attributes['mime_types'])) { $types[] = $type; } } return $types; }
[ "public", "function", "possibleAggregateTypesForMimeType", "(", "$", "mime", ")", "{", "$", "types", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "config", "[", "'aggregate_types'", "]", "as", "$", "type", "=>", "$", "attributes", ")", "{", "if...
Determine the aggregate type of the file based on the MIME type. @param string $mime @return string[]
[ "Determine", "the", "aggregate", "type", "of", "the", "file", "based", "on", "the", "MIME", "type", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L417-L427
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.possibleAggregateTypesForExtension
public function possibleAggregateTypesForExtension($extension) { $types = []; foreach ($this->config['aggregate_types'] as $type => $attributes) { if (in_array($extension, $attributes['extensions'])) { $types[] = $type; } } return $types; }
php
public function possibleAggregateTypesForExtension($extension) { $types = []; foreach ($this->config['aggregate_types'] as $type => $attributes) { if (in_array($extension, $attributes['extensions'])) { $types[] = $type; } } return $types; }
[ "public", "function", "possibleAggregateTypesForExtension", "(", "$", "extension", ")", "{", "$", "types", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "config", "[", "'aggregate_types'", "]", "as", "$", "type", "=>", "$", "attributes", ")", "{",...
Determine the aggregate type of the file based on the extension. @param string $extension @return string[]
[ "Determine", "the", "aggregate", "type", "of", "the", "file", "based", "on", "the", "extension", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L434-L444
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.upload
public function upload() { $this->verifyFile(); $model = $this->makeModel(); $model->size = $this->source->size(); $model->mime_type = $this->source->mimeType(); $model->extension = $this->source->extension(); $model->aggregate_type = $this->inferAggregateType($model->mime_type, $model->extension); $model->disk = $this->disk ?: $this->config['default_disk']; $model->directory = $this->directory; $model->filename = $this->generateFilename(); $model = $this->handleDuplicate($model); if (is_callable($this->before_save)) { call_user_func($this->before_save, $model, $this->source); } $this->filesystem->disk($model->disk)->put($model->getDiskPath(), $this->source->contents()); $model->save(); return $model; }
php
public function upload() { $this->verifyFile(); $model = $this->makeModel(); $model->size = $this->source->size(); $model->mime_type = $this->source->mimeType(); $model->extension = $this->source->extension(); $model->aggregate_type = $this->inferAggregateType($model->mime_type, $model->extension); $model->disk = $this->disk ?: $this->config['default_disk']; $model->directory = $this->directory; $model->filename = $this->generateFilename(); $model = $this->handleDuplicate($model); if (is_callable($this->before_save)) { call_user_func($this->before_save, $model, $this->source); } $this->filesystem->disk($model->disk)->put($model->getDiskPath(), $this->source->contents()); $model->save(); return $model; }
[ "public", "function", "upload", "(", ")", "{", "$", "this", "->", "verifyFile", "(", ")", ";", "$", "model", "=", "$", "this", "->", "makeModel", "(", ")", ";", "$", "model", "->", "size", "=", "$", "this", "->", "source", "->", "size", "(", ")",...
Process the file upload. Validates the source, then stores the file onto the disk and creates and stores a new Media instance. @return \Plank\Mediable\Media @throws \Plank\Mediable\Exceptions\MediaUpload\ConfigurationException @throws \Plank\Mediable\Exceptions\MediaUpload\FileExistsException @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotFoundException @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotSupportedException @throws \Plank\Mediable\Exceptions\MediaUpload\FileSizeException
[ "Process", "the", "file", "upload", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L458-L484
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.update
public function update(Media $media) { $storage = $this->filesystem->disk($media->disk); $media->size = $this->verifyFileSize($storage->size($media->getDiskPath())); $media->mime_type = $this->verifyMimeType($storage->mimeType($media->getDiskPath())); $media->aggregate_type = $this->inferAggregateType($media->mime_type, $media->extension); if ($dirty = $media->isDirty()) { $media->save(); } return $dirty; }
php
public function update(Media $media) { $storage = $this->filesystem->disk($media->disk); $media->size = $this->verifyFileSize($storage->size($media->getDiskPath())); $media->mime_type = $this->verifyMimeType($storage->mimeType($media->getDiskPath())); $media->aggregate_type = $this->inferAggregateType($media->mime_type, $media->extension); if ($dirty = $media->isDirty()) { $media->save(); } return $dirty; }
[ "public", "function", "update", "(", "Media", "$", "media", ")", "{", "$", "storage", "=", "$", "this", "->", "filesystem", "->", "disk", "(", "$", "media", "->", "disk", ")", ";", "$", "media", "->", "size", "=", "$", "this", "->", "verifyFileSize",...
Reanalyze a media record's file and adjust the aggregate type and size, if necessary. @param \Plank\Mediable\Media $media @return bool Whether the model was modified @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotSupportedException @throws \Plank\Mediable\Exceptions\MediaUpload\FileSizeException
[ "Reanalyze", "a", "media", "record", "s", "file", "and", "adjust", "the", "aggregate", "type", "and", "size", "if", "necessary", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L567-L580
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.verifyFile
public function verifyFile() { $this->verifySource(); $this->verifyFileSize($this->source->size()); $this->verifyMimeType($this->source->mimeType()); $this->verifyExtension($this->source->extension()); }
php
public function verifyFile() { $this->verifySource(); $this->verifyFileSize($this->source->size()); $this->verifyMimeType($this->source->mimeType()); $this->verifyExtension($this->source->extension()); }
[ "public", "function", "verifyFile", "(", ")", "{", "$", "this", "->", "verifySource", "(", ")", ";", "$", "this", "->", "verifyFileSize", "(", "$", "this", "->", "source", "->", "size", "(", ")", ")", ";", "$", "this", "->", "verifyMimeType", "(", "$...
Verify if file is valid @throws \Plank\Mediable\Exceptions\MediaUpload\ConfigurationException If no source is provided @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotFoundException If the source is invalid @throws \Plank\Mediable\Exceptions\MediaUpload\FileSizeException If the file is too large @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotSupportedException If the mime type is not allowed @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotSupportedException If the file extension is not allowed @return void
[ "Verify", "if", "file", "is", "valid" ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L591-L597
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.verifyDisk
private function verifyDisk($disk) { if (! array_key_exists($disk, config('filesystems.disks'))) { throw ConfigurationException::diskNotFound($disk); } if (! in_array($disk, $this->config['allowed_disks'])) { throw ForbiddenException::diskNotAllowed($disk); } return $disk; }
php
private function verifyDisk($disk) { if (! array_key_exists($disk, config('filesystems.disks'))) { throw ConfigurationException::diskNotFound($disk); } if (! in_array($disk, $this->config['allowed_disks'])) { throw ForbiddenException::diskNotAllowed($disk); } return $disk; }
[ "private", "function", "verifyDisk", "(", "$", "disk", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "disk", ",", "config", "(", "'filesystems.disks'", ")", ")", ")", "{", "throw", "ConfigurationException", "::", "diskNotFound", "(", "$", "disk", ...
Ensure that the provided filesystem disk name exists and is allowed. @param string $disk @return string @throws \Plank\Mediable\Exceptions\MediaUpload\ConfigurationException If the disk does not exist @throws \Plank\Mediable\Exceptions\MediaUpload\ForbiddenException If the disk is not included in the `allowed_disks` config.
[ "Ensure", "that", "the", "provided", "filesystem", "disk", "name", "exists", "and", "is", "allowed", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L617-L628
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.verifySource
private function verifySource() { if (empty($this->source)) { throw ConfigurationException::noSourceProvided(); } if (! $this->source->valid()) { throw FileNotFoundException::fileNotFound($this->source->path()); } }
php
private function verifySource() { if (empty($this->source)) { throw ConfigurationException::noSourceProvided(); } if (! $this->source->valid()) { throw FileNotFoundException::fileNotFound($this->source->path()); } }
[ "private", "function", "verifySource", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "source", ")", ")", "{", "throw", "ConfigurationException", "::", "noSourceProvided", "(", ")", ";", "}", "if", "(", "!", "$", "this", "->", "source", "->...
Ensure that a valid source has been provided. @return void @throws \Plank\Mediable\Exceptions\MediaUpload\ConfigurationException If no source is provided @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotFoundException If the source is invalid
[ "Ensure", "that", "a", "valid", "source", "has", "been", "provided", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L636-L644
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.verifyMimeType
private function verifyMimeType($mime_type) { $allowed = $this->config['allowed_mime_types']; if (! empty($allowed) && ! in_array(strtolower($mime_type), $allowed)) { throw FileNotSupportedException::mimeRestricted(strtolower($mime_type), $allowed); } return $mime_type; }
php
private function verifyMimeType($mime_type) { $allowed = $this->config['allowed_mime_types']; if (! empty($allowed) && ! in_array(strtolower($mime_type), $allowed)) { throw FileNotSupportedException::mimeRestricted(strtolower($mime_type), $allowed); } return $mime_type; }
[ "private", "function", "verifyMimeType", "(", "$", "mime_type", ")", "{", "$", "allowed", "=", "$", "this", "->", "config", "[", "'allowed_mime_types'", "]", ";", "if", "(", "!", "empty", "(", "$", "allowed", ")", "&&", "!", "in_array", "(", "strtolower"...
Ensure that the file's mime type is allowed. @param string $mime_type @return string @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotSupportedException If the mime type is not allowed
[ "Ensure", "that", "the", "file", "s", "mime", "type", "is", "allowed", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L652-L660
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.verifyExtension
private function verifyExtension($extension) { $allowed = $this->config['allowed_extensions']; if (! empty($allowed) && ! in_array(strtolower($extension), $allowed)) { throw FileNotSupportedException::extensionRestricted(strtolower($extension), $allowed); } return $extension; }
php
private function verifyExtension($extension) { $allowed = $this->config['allowed_extensions']; if (! empty($allowed) && ! in_array(strtolower($extension), $allowed)) { throw FileNotSupportedException::extensionRestricted(strtolower($extension), $allowed); } return $extension; }
[ "private", "function", "verifyExtension", "(", "$", "extension", ")", "{", "$", "allowed", "=", "$", "this", "->", "config", "[", "'allowed_extensions'", "]", ";", "if", "(", "!", "empty", "(", "$", "allowed", ")", "&&", "!", "in_array", "(", "strtolower...
Ensure that the file's extension is allowed. @param string $extension @return string @throws \Plank\Mediable\Exceptions\MediaUpload\FileNotSupportedException If the file extension is not allowed
[ "Ensure", "that", "the", "file", "s", "extension", "is", "allowed", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L668-L676
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.verifyFileSize
private function verifyFileSize($size) { $max = $this->config['max_size']; if ($max > 0 && $size > $max) { throw FileSizeException::fileIsTooBig($size, $max); } return $size; }
php
private function verifyFileSize($size) { $max = $this->config['max_size']; if ($max > 0 && $size > $max) { throw FileSizeException::fileIsTooBig($size, $max); } return $size; }
[ "private", "function", "verifyFileSize", "(", "$", "size", ")", "{", "$", "max", "=", "$", "this", "->", "config", "[", "'max_size'", "]", ";", "if", "(", "$", "max", ">", "0", "&&", "$", "size", ">", "$", "max", ")", "{", "throw", "FileSizeExcepti...
Verify that the file being uploaded is not larger than the maximum. @param int $size @return int @throws \Plank\Mediable\Exceptions\MediaUpload\FileSizeException If the file is too large
[ "Verify", "that", "the", "file", "being", "uploaded", "is", "not", "larger", "than", "the", "maximum", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L684-L692
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.handleDuplicate
private function handleDuplicate(Media $model) { if ($this->filesystem->disk($model->disk)->has($model->getDiskPath())) { switch ($this->config['on_duplicate']) { case static::ON_DUPLICATE_ERROR: throw FileExistsException::fileExists($model->getDiskPath()); break; case static::ON_DUPLICATE_REPLACE: $this->deleteExistingMedia($model); break; case static::ON_DUPLICATE_UPDATE: $this->deleteExistingFile($model); $model->{$model->getKeyName()} = Media::forPathOnDisk( $model->disk, $model->getDiskPath()) ->pluck($model->getKeyName())->first(); $model->exists = true; break; case static::ON_DUPLICATE_INCREMENT: default: $model->filename = $this->generateUniqueFilename($model); } } return $model; }
php
private function handleDuplicate(Media $model) { if ($this->filesystem->disk($model->disk)->has($model->getDiskPath())) { switch ($this->config['on_duplicate']) { case static::ON_DUPLICATE_ERROR: throw FileExistsException::fileExists($model->getDiskPath()); break; case static::ON_DUPLICATE_REPLACE: $this->deleteExistingMedia($model); break; case static::ON_DUPLICATE_UPDATE: $this->deleteExistingFile($model); $model->{$model->getKeyName()} = Media::forPathOnDisk( $model->disk, $model->getDiskPath()) ->pluck($model->getKeyName())->first(); $model->exists = true; break; case static::ON_DUPLICATE_INCREMENT: default: $model->filename = $this->generateUniqueFilename($model); } } return $model; }
[ "private", "function", "handleDuplicate", "(", "Media", "$", "model", ")", "{", "if", "(", "$", "this", "->", "filesystem", "->", "disk", "(", "$", "model", "->", "disk", ")", "->", "has", "(", "$", "model", "->", "getDiskPath", "(", ")", ")", ")", ...
Decide what to do about duplicated files. @param \Plank\Mediable\Media $model @return \Plank\Mediable\Media @throws \Plank\Mediable\Exceptions\MediaUpload\FileExistsException If directory is not writable or file already exists at the destination and on_duplicate is set to 'error'
[ "Decide", "what", "to", "do", "about", "duplicated", "files", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L701-L724
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.deleteExistingMedia
private function deleteExistingMedia(Media $model) { Media::where('disk', $model->disk) ->where('directory', $model->directory) ->where('filename', $model->filename) ->where('extension', $model->extension) ->delete(); $this->deleteExistingFile($model); }
php
private function deleteExistingMedia(Media $model) { Media::where('disk', $model->disk) ->where('directory', $model->directory) ->where('filename', $model->filename) ->where('extension', $model->extension) ->delete(); $this->deleteExistingFile($model); }
[ "private", "function", "deleteExistingMedia", "(", "Media", "$", "model", ")", "{", "Media", "::", "where", "(", "'disk'", ",", "$", "model", "->", "disk", ")", "->", "where", "(", "'directory'", ",", "$", "model", "->", "directory", ")", "->", "where", ...
Delete the media that previously existed at a destination. @param \Plank\Mediable\Media $model @return void
[ "Delete", "the", "media", "that", "previously", "existed", "at", "a", "destination", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L731-L740
train
plank/laravel-mediable
src/MediaUploader.php
MediaUploader.deleteExistingFile
private function deleteExistingFile(Media $model) { $this->filesystem->disk($model->disk)->delete($model->getDiskPath()); }
php
private function deleteExistingFile(Media $model) { $this->filesystem->disk($model->disk)->delete($model->getDiskPath()); }
[ "private", "function", "deleteExistingFile", "(", "Media", "$", "model", ")", "{", "$", "this", "->", "filesystem", "->", "disk", "(", "$", "model", "->", "disk", ")", "->", "delete", "(", "$", "model", "->", "getDiskPath", "(", ")", ")", ";", "}" ]
Delete the file on disk. @param \Plank\Mediable\Media $model @return void
[ "Delete", "the", "file", "on", "disk", "." ]
034b79452aac0e9e0a42372af21cd8dfe83a6da2
https://github.com/plank/laravel-mediable/blob/034b79452aac0e9e0a42372af21cd8dfe83a6da2/src/MediaUploader.php#L747-L750
train