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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
BKWLD/decoy | classes/Controllers/Base.php | Base.index | public function index()
{
// Look for overriden views
$this->overrideViews();
// Get models to show
$results = $this->makeIndexQuery()->paginate($this->perPage());
// Render the view using the `listing` builder
$listing = Listing::createFromController($this, $results);
if ($this->parent) {
$listing->parent($this->parent);
// The layout header may have a many to many autocomplete
$this->layout->with($this->autocompleteViewVars());
}
// Render view
return $this->populateView($listing);
} | php | public function index()
{
// Look for overriden views
$this->overrideViews();
// Get models to show
$results = $this->makeIndexQuery()->paginate($this->perPage());
// Render the view using the `listing` builder
$listing = Listing::createFromController($this, $results);
if ($this->parent) {
$listing->parent($this->parent);
// The layout header may have a many to many autocomplete
$this->layout->with($this->autocompleteViewVars());
}
// Render view
return $this->populateView($listing);
} | [
"public",
"function",
"index",
"(",
")",
"{",
"// Look for overriden views",
"$",
"this",
"->",
"overrideViews",
"(",
")",
";",
"// Get models to show",
"$",
"results",
"=",
"$",
"this",
"->",
"makeIndexQuery",
"(",
")",
"->",
"paginate",
"(",
"$",
"this",
"... | Show an index, listing page. Sets view via the layout.
@return Illuminate\Contracts\View\Factory | [
"Show",
"an",
"index",
"listing",
"page",
".",
"Sets",
"view",
"via",
"the",
"layout",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L440-L459 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.create | public function create()
{
// Look for overriden views
$this->overrideViews();
// Pass validation through
Former::withRules($this->getRules());
// Initialize localization
with($localize = new Localize)
->model($this->model)
->title(Str::singular($this->title));
// Make the sidebar
$sidebar = new Sidebar;
if (!$localize->hidden()) {
$sidebar->addToEnd($localize);
}
// Render view
return $this->populateView($this->show_view, [
'item' => null,
'localize' => $localize,
'sidebar' => $sidebar,
'parent_id' => $this->parent ? $this->parent->getKey() : null,
]);
} | php | public function create()
{
// Look for overriden views
$this->overrideViews();
// Pass validation through
Former::withRules($this->getRules());
// Initialize localization
with($localize = new Localize)
->model($this->model)
->title(Str::singular($this->title));
// Make the sidebar
$sidebar = new Sidebar;
if (!$localize->hidden()) {
$sidebar->addToEnd($localize);
}
// Render view
return $this->populateView($this->show_view, [
'item' => null,
'localize' => $localize,
'sidebar' => $sidebar,
'parent_id' => $this->parent ? $this->parent->getKey() : null,
]);
} | [
"public",
"function",
"create",
"(",
")",
"{",
"// Look for overriden views",
"$",
"this",
"->",
"overrideViews",
"(",
")",
";",
"// Pass validation through",
"Former",
"::",
"withRules",
"(",
"$",
"this",
"->",
"getRules",
"(",
")",
")",
";",
"// Initialize loc... | Show the create form. Sets view via the layout.
@return Illuminate\Contracts\View\Factory | [
"Show",
"the",
"create",
"form",
".",
"Sets",
"view",
"via",
"the",
"layout",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L466-L492 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.store | public function store()
{
// Create a new object
$item = new $this->model;
// Remove nested model data from input and prepare to insert on save
$input = (new NestedModels)->relateTo($item);
// Hydrate the object
$item->fill($input);
// Validate and save.
$this->validate($item);
if ($this->parent) {
$this->parent->{$this->parent_to_self}()->save($item);
} else {
$item->save();
}
// Redirect to edit view
if (Request::ajax()) {
return Response::json(['id' => $item->id]);
} else {
return Redirect::to(DecoyURL::relative('edit', $item->id))
->with('success', $this->successMessage($item, 'created'));
}
} | php | public function store()
{
// Create a new object
$item = new $this->model;
// Remove nested model data from input and prepare to insert on save
$input = (new NestedModels)->relateTo($item);
// Hydrate the object
$item->fill($input);
// Validate and save.
$this->validate($item);
if ($this->parent) {
$this->parent->{$this->parent_to_self}()->save($item);
} else {
$item->save();
}
// Redirect to edit view
if (Request::ajax()) {
return Response::json(['id' => $item->id]);
} else {
return Redirect::to(DecoyURL::relative('edit', $item->id))
->with('success', $this->successMessage($item, 'created'));
}
} | [
"public",
"function",
"store",
"(",
")",
"{",
"// Create a new object",
"$",
"item",
"=",
"new",
"$",
"this",
"->",
"model",
";",
"// Remove nested model data from input and prepare to insert on save",
"$",
"input",
"=",
"(",
"new",
"NestedModels",
")",
"->",
"relat... | Store a new record
@return Symfony\Component\HttpFoundation\Response Redirect to edit view | [
"Store",
"a",
"new",
"record"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L499-L525 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.edit | public function edit($id)
{
// Get the model instance
$item = $this->findOrFail($id);
// Respond to AJAX requests for a single item with JSON
if (Request::ajax()) {
return Response::json($item);
}
// Look for overriden views
$this->overrideViews();
// Populate form
Former::populate($item);
Former::withRules($this->getRules());
// Initialize localization
with($localize = new Localize)
->item($item)
->title(Str::singular($this->title));
// Make the sidebar
$sidebar = new Sidebar($item);
if (!$localize->hidden()) {
$sidebar->addToEnd($localize);
}
// Render view
return $this->populateView($this->show_view, [
'item' => $item,
'localize' => $localize,
'sidebar' => $sidebar,
'parent_id' => $this->parent ? $this->parent->getKey() : null,
]);
} | php | public function edit($id)
{
// Get the model instance
$item = $this->findOrFail($id);
// Respond to AJAX requests for a single item with JSON
if (Request::ajax()) {
return Response::json($item);
}
// Look for overriden views
$this->overrideViews();
// Populate form
Former::populate($item);
Former::withRules($this->getRules());
// Initialize localization
with($localize = new Localize)
->item($item)
->title(Str::singular($this->title));
// Make the sidebar
$sidebar = new Sidebar($item);
if (!$localize->hidden()) {
$sidebar->addToEnd($localize);
}
// Render view
return $this->populateView($this->show_view, [
'item' => $item,
'localize' => $localize,
'sidebar' => $sidebar,
'parent_id' => $this->parent ? $this->parent->getKey() : null,
]);
} | [
"public",
"function",
"edit",
"(",
"$",
"id",
")",
"{",
"// Get the model instance",
"$",
"item",
"=",
"$",
"this",
"->",
"findOrFail",
"(",
"$",
"id",
")",
";",
"// Respond to AJAX requests for a single item with JSON",
"if",
"(",
"Request",
"::",
"ajax",
"(",
... | Show the edit form. Sets view via the layout.
@param int $id Model key
@return Illuminate\Contracts\View\Factory | [
"Show",
"the",
"edit",
"form",
".",
"Sets",
"view",
"via",
"the",
"layout",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L533-L568 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.destroy | public function destroy($id)
{
// Find the item
$item = $this->findOrFail($id);
// Delete row (this should trigger file attachment deletes as well)
$item->delete();
// As long as not an ajax request, go back to the parent directory of the referrer
if (Request::ajax()) {
return Response::json();
} else {
return Redirect::to(DecoyURL::relative('index'))
->with('success', $this->successMessage($item, 'deleted'));
}
} | php | public function destroy($id)
{
// Find the item
$item = $this->findOrFail($id);
// Delete row (this should trigger file attachment deletes as well)
$item->delete();
// As long as not an ajax request, go back to the parent directory of the referrer
if (Request::ajax()) {
return Response::json();
} else {
return Redirect::to(DecoyURL::relative('index'))
->with('success', $this->successMessage($item, 'deleted'));
}
} | [
"public",
"function",
"destroy",
"(",
"$",
"id",
")",
"{",
"// Find the item",
"$",
"item",
"=",
"$",
"this",
"->",
"findOrFail",
"(",
"$",
"id",
")",
";",
"// Delete row (this should trigger file attachment deletes as well)",
"$",
"item",
"->",
"delete",
"(",
"... | Destroy a record
@param int $id Model key
@return Symfony\Component\HttpFoundation\Response Redirect to listing | [
"Destroy",
"a",
"record"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L619-L634 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.duplicate | public function duplicate($id)
{
// Find the source item
$src = $this->findOrFail($id);
if (empty($src->cloneable)) {
return App::abort(404);
}
// Duplicate using Bkwld\Cloner
$new = $src->duplicate();
// Don't make duplicates public
if (array_key_exists('public', $new->getAttributes())) {
$this->public = 0;
}
// If there is a name or title field, append " copy" to it. Use "original"
// to avoid mutators.
if ($name = $new->getOriginal('name')) {
$new->setAttribute('name', $name.' copy');
} elseif ($title = $new->getOriginal('title')) {
$new->setAttribute('title', $title.' copy');
}
// Set localization options on new instance
if ($locale = request('locale')) {
$new->locale = $locale;
if (isset($src->locale_group)) {
$new->locale_group = $src->locale_group;
}
}
// Save any changes that were made
$new->save();
// Save the new record and redirect to its edit view
return Redirect::to(DecoyURL::relative('edit', $new->getKey()))
->with('success', $this->successMessage($src, 'duplicated'));
} | php | public function duplicate($id)
{
// Find the source item
$src = $this->findOrFail($id);
if (empty($src->cloneable)) {
return App::abort(404);
}
// Duplicate using Bkwld\Cloner
$new = $src->duplicate();
// Don't make duplicates public
if (array_key_exists('public', $new->getAttributes())) {
$this->public = 0;
}
// If there is a name or title field, append " copy" to it. Use "original"
// to avoid mutators.
if ($name = $new->getOriginal('name')) {
$new->setAttribute('name', $name.' copy');
} elseif ($title = $new->getOriginal('title')) {
$new->setAttribute('title', $title.' copy');
}
// Set localization options on new instance
if ($locale = request('locale')) {
$new->locale = $locale;
if (isset($src->locale_group)) {
$new->locale_group = $src->locale_group;
}
}
// Save any changes that were made
$new->save();
// Save the new record and redirect to its edit view
return Redirect::to(DecoyURL::relative('edit', $new->getKey()))
->with('success', $this->successMessage($src, 'duplicated'));
} | [
"public",
"function",
"duplicate",
"(",
"$",
"id",
")",
"{",
"// Find the source item",
"$",
"src",
"=",
"$",
"this",
"->",
"findOrFail",
"(",
"$",
"id",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"src",
"->",
"cloneable",
")",
")",
"{",
"return",
"App"... | Duplicate a record
@param int $id Model key
@return Symfony\Component\HttpFoundation\Response Redirect to new record | [
"Duplicate",
"a",
"record"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L646-L684 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.autocomplete | public function autocomplete()
{
// Do nothing if the query is too short
if (strlen(request('query')) < 1) {
return Response::json();
}
// Get an instance so the title attributes can be found. If none are found,
// then there are no results, so bounce
if (!$model = call_user_func([$this->model, 'first'])) {
return Response::json($this->formatAutocompleteResponse([]));
}
// Get data matching the query
$query = call_user_func([$this->model, 'titleContains'], request('query'))
->ordered()
->take(15); // Note, this is also enforced in the autocomplete.js
// Don't return any rows already attached to the parent. So make sure the
// id is not already in the pivot table for the parent
if ($this->isChildInManyToMany()) {
// See if there is an exact match on what's been entered. This is useful
// for many to manys with tags because we want to know if the reason that
// autocomplete returns no results on an exact match that is already
// attached is because it already exists. Otherwise, it would allow the
// user to create the tag
if ($this->parentRelation()
->titleContains(request('query'), true)
->count()) {
return Response::json(['exists' => true]);
}
// Get the ids of already attached rows through the relationship function.
// There are ways to do just in SQL but then we lose the ability for the
// relationship function to apply conditions, like is done in polymoprhic
// relationships.
$siblings = $this->parentRelation()->get();
if (count($siblings)) {
$sibling_ids = [];
foreach ($siblings as $sibling) {
$sibling_ids[] = $sibling->id;
}
// Add condition to query
$model = new $this->model;
$query = $query->whereNotIn($model->getQualifiedKeyName(), $sibling_ids);
}
}
// Return result
return Response::json($this->formatAutocompleteResponse($query->get()));
} | php | public function autocomplete()
{
// Do nothing if the query is too short
if (strlen(request('query')) < 1) {
return Response::json();
}
// Get an instance so the title attributes can be found. If none are found,
// then there are no results, so bounce
if (!$model = call_user_func([$this->model, 'first'])) {
return Response::json($this->formatAutocompleteResponse([]));
}
// Get data matching the query
$query = call_user_func([$this->model, 'titleContains'], request('query'))
->ordered()
->take(15); // Note, this is also enforced in the autocomplete.js
// Don't return any rows already attached to the parent. So make sure the
// id is not already in the pivot table for the parent
if ($this->isChildInManyToMany()) {
// See if there is an exact match on what's been entered. This is useful
// for many to manys with tags because we want to know if the reason that
// autocomplete returns no results on an exact match that is already
// attached is because it already exists. Otherwise, it would allow the
// user to create the tag
if ($this->parentRelation()
->titleContains(request('query'), true)
->count()) {
return Response::json(['exists' => true]);
}
// Get the ids of already attached rows through the relationship function.
// There are ways to do just in SQL but then we lose the ability for the
// relationship function to apply conditions, like is done in polymoprhic
// relationships.
$siblings = $this->parentRelation()->get();
if (count($siblings)) {
$sibling_ids = [];
foreach ($siblings as $sibling) {
$sibling_ids[] = $sibling->id;
}
// Add condition to query
$model = new $this->model;
$query = $query->whereNotIn($model->getQualifiedKeyName(), $sibling_ids);
}
}
// Return result
return Response::json($this->formatAutocompleteResponse($query->get()));
} | [
"public",
"function",
"autocomplete",
"(",
")",
"{",
"// Do nothing if the query is too short",
"if",
"(",
"strlen",
"(",
"request",
"(",
"'query'",
")",
")",
"<",
"1",
")",
"{",
"return",
"Response",
"::",
"json",
"(",
")",
";",
"}",
"// Get an instance so th... | List as JSON for autocomplete widgets
@return Illuminate\Http\Response JSON | [
"List",
"as",
"JSON",
"for",
"autocomplete",
"widgets"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L695-L747 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.autocompleteViewVars | public function autocompleteViewVars()
{
if (!$this->parent) {
return [];
}
$parent_controller = new $this->parent_controller;
return [
'parent_id' => $this->parent->getKey(),
'parent_controller' => $this->parent_controller,
'parent_controller_title' => $parent_controller->title(),
'parent_controller_description' => $parent_controller->description(),
'many_to_many' => $this->isChildInManyToMany(),
];
} | php | public function autocompleteViewVars()
{
if (!$this->parent) {
return [];
}
$parent_controller = new $this->parent_controller;
return [
'parent_id' => $this->parent->getKey(),
'parent_controller' => $this->parent_controller,
'parent_controller_title' => $parent_controller->title(),
'parent_controller_description' => $parent_controller->description(),
'many_to_many' => $this->isChildInManyToMany(),
];
} | [
"public",
"function",
"autocompleteViewVars",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"parent",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"parent_controller",
"=",
"new",
"$",
"this",
"->",
"parent_controller",
";",
"return",
"[",
"'parent_i... | Return key-val pairs needed for view partials related to many to many
autocompletes
@return array key-val pairs | [
"Return",
"key",
"-",
"val",
"pairs",
"needed",
"for",
"view",
"partials",
"related",
"to",
"many",
"to",
"many",
"autocompletes"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L755-L770 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.attach | public function attach($id)
{
// Require there to be a parent id and a valid id for the resource
$item = $this->findOrFail($id);
// Do the attach
$item->fireDecoyEvent('attaching', [$item, $this->parent]);
$item->{$this->self_to_parent}()->attach($this->parent);
$item->fireDecoyEvent('attached', [$item, $this->parent]);
// Return the response
return Response::json();
} | php | public function attach($id)
{
// Require there to be a parent id and a valid id for the resource
$item = $this->findOrFail($id);
// Do the attach
$item->fireDecoyEvent('attaching', [$item, $this->parent]);
$item->{$this->self_to_parent}()->attach($this->parent);
$item->fireDecoyEvent('attached', [$item, $this->parent]);
// Return the response
return Response::json();
} | [
"public",
"function",
"attach",
"(",
"$",
"id",
")",
"{",
"// Require there to be a parent id and a valid id for the resource",
"$",
"item",
"=",
"$",
"this",
"->",
"findOrFail",
"(",
"$",
"id",
")",
";",
"// Do the attach",
"$",
"item",
"->",
"fireDecoyEvent",
"(... | Attach a model to a parent_id, like with a many to many style
autocomplete widget
@param int $id The id of the parent model
@return Illuminate\Http\Response JSON | [
"Attach",
"a",
"model",
"to",
"a",
"parent_id",
"like",
"with",
"a",
"many",
"to",
"many",
"style",
"autocomplete",
"widget"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L779-L791 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.remove | public function remove($id)
{
// Support removing many ids at once
$ids = Request::has('ids') ? explode(',', request('ids')) : [$id];
// Get the model instances for each id, for the purpose of event firing
$items = array_map(function ($id) {
return $this->findOrFail($id);
}, $ids);
// Lookup up the parent model so we can bulk remove multiple of THIS model
foreach ($items as $item) {
$item->fireDecoyEvent('removing', [$item, $this->parent]);
}
$this->parentRelation()->detach($ids);
foreach ($items as $item) {
$item->fireDecoyEvent('removed', [$item, $this->parent]);
}
// Redirect. We can use back cause this is never called from a "show"
// page like get_delete is.
if (Request::ajax()) {
return Response::json();
}
return Redirect::back();
} | php | public function remove($id)
{
// Support removing many ids at once
$ids = Request::has('ids') ? explode(',', request('ids')) : [$id];
// Get the model instances for each id, for the purpose of event firing
$items = array_map(function ($id) {
return $this->findOrFail($id);
}, $ids);
// Lookup up the parent model so we can bulk remove multiple of THIS model
foreach ($items as $item) {
$item->fireDecoyEvent('removing', [$item, $this->parent]);
}
$this->parentRelation()->detach($ids);
foreach ($items as $item) {
$item->fireDecoyEvent('removed', [$item, $this->parent]);
}
// Redirect. We can use back cause this is never called from a "show"
// page like get_delete is.
if (Request::ajax()) {
return Response::json();
}
return Redirect::back();
} | [
"public",
"function",
"remove",
"(",
"$",
"id",
")",
"{",
"// Support removing many ids at once",
"$",
"ids",
"=",
"Request",
"::",
"has",
"(",
"'ids'",
")",
"?",
"explode",
"(",
"','",
",",
"request",
"(",
"'ids'",
")",
")",
":",
"[",
"$",
"id",
"]",
... | Remove a relationship. Very similar to delete, except that we're
not actually deleting from the database
@param mixed $id One or many (commaa delimited) parent ids
@return Illuminate\Http\Response Either a JSON or Redirect response | [
"Remove",
"a",
"relationship",
".",
"Very",
"similar",
"to",
"delete",
"except",
"that",
"we",
"re",
"not",
"actually",
"deleting",
"from",
"the",
"database"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L799-L825 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.makeIndexQuery | protected function makeIndexQuery()
{
// Open up the query. We can assume that Model has an ordered() function
// because it's defined on Decoy's Base_Model
$query = $this->parent ?
$this->parentRelation()->ordered() :
call_user_func([$this->model, 'ordered']);
// Allow trashed records
if ($this->withTrashed()) {
$query->withTrashed();
}
// Apply search
$search = new Search();
$query = $search->apply($query, $this->search());
return $query;
} | php | protected function makeIndexQuery()
{
// Open up the query. We can assume that Model has an ordered() function
// because it's defined on Decoy's Base_Model
$query = $this->parent ?
$this->parentRelation()->ordered() :
call_user_func([$this->model, 'ordered']);
// Allow trashed records
if ($this->withTrashed()) {
$query->withTrashed();
}
// Apply search
$search = new Search();
$query = $search->apply($query, $this->search());
return $query;
} | [
"protected",
"function",
"makeIndexQuery",
"(",
")",
"{",
"// Open up the query. We can assume that Model has an ordered() function",
"// because it's defined on Decoy's Base_Model",
"$",
"query",
"=",
"$",
"this",
"->",
"parent",
"?",
"$",
"this",
"->",
"parentRelation",
"("... | Make the index query, including applying a search
@return \Illuminate\Database\Eloquent\Builder | [
"Make",
"the",
"index",
"query",
"including",
"applying",
"a",
"search"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L836-L853 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.findOrFail | protected function findOrFail($id)
{
$model = $this->model;
if ($this->withTrashed()) {
return $model::withTrashed()->findOrFail($id);
} else {
return $model::findOrFail($id);
}
} | php | protected function findOrFail($id)
{
$model = $this->model;
if ($this->withTrashed()) {
return $model::withTrashed()->findOrFail($id);
} else {
return $model::findOrFail($id);
}
} | [
"protected",
"function",
"findOrFail",
"(",
"$",
"id",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"model",
";",
"if",
"(",
"$",
"this",
"->",
"withTrashed",
"(",
")",
")",
"{",
"return",
"$",
"model",
"::",
"withTrashed",
"(",
")",
"->",
"find... | Helper for getting a model instance by ID
@param scalar $id
@return Eloquent\Model | [
"Helper",
"for",
"getting",
"a",
"model",
"instance",
"by",
"ID"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L861-L869 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.validate | protected function validate($data, $rules = null, $messages = [])
{
// A request may be passed in when using Laravel traits, like how resetting
// passwords work. Get the input from it
if (is_a($data, \Illuminate\Http\Request::class)) {
$data = $data->input();
}
// Get validation rules from model
$model = null;
if (is_a($data, BaseModel::class)) {
$model = $data;
$data = $model->getAttributes();
if (empty($rules)) {
$rules = $model::$rules;
}
}
// If an AJAX update, don't require all fields to be present. Pass just the
// keys of the input to the array_only function to filter the rules list.
if (Request::ajax() && Request::getMethod() == 'PUT') {
$rules = array_only($rules, array_keys(request()->input()));
}
// Stop if no rules
if (empty($rules)) {
return;
}
// Build the validation instance and fire the intiating event.
if ($model) {
(new ModelValidator)->validate($model, $rules, $messages);
} else {
$messages = array_merge(BkwldLibraryValidator::$messages, $messages);
$validation = Validator::make($data, $rules, $messages);
if ($validation->fails()) {
throw new ValidationFail($validation);
}
}
} | php | protected function validate($data, $rules = null, $messages = [])
{
// A request may be passed in when using Laravel traits, like how resetting
// passwords work. Get the input from it
if (is_a($data, \Illuminate\Http\Request::class)) {
$data = $data->input();
}
// Get validation rules from model
$model = null;
if (is_a($data, BaseModel::class)) {
$model = $data;
$data = $model->getAttributes();
if (empty($rules)) {
$rules = $model::$rules;
}
}
// If an AJAX update, don't require all fields to be present. Pass just the
// keys of the input to the array_only function to filter the rules list.
if (Request::ajax() && Request::getMethod() == 'PUT') {
$rules = array_only($rules, array_keys(request()->input()));
}
// Stop if no rules
if (empty($rules)) {
return;
}
// Build the validation instance and fire the intiating event.
if ($model) {
(new ModelValidator)->validate($model, $rules, $messages);
} else {
$messages = array_merge(BkwldLibraryValidator::$messages, $messages);
$validation = Validator::make($data, $rules, $messages);
if ($validation->fails()) {
throw new ValidationFail($validation);
}
}
} | [
"protected",
"function",
"validate",
"(",
"$",
"data",
",",
"$",
"rules",
"=",
"null",
",",
"$",
"messages",
"=",
"[",
"]",
")",
"{",
"// A request may be passed in when using Laravel traits, like how resetting",
"// passwords work. Get the input from it",
"if",
"(",
"... | All actions validate in basically the same way. This is shared logic for that
@param BaseModel|Request|array $data
@param array $rules A Laravel rules array. If null, will be pulled from model
@param array $messages Special error messages
@return void
@throws ValidationFail | [
"All",
"actions",
"validate",
"in",
"basically",
"the",
"same",
"way",
".",
"This",
"is",
"shared",
"logic",
"for",
"that"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L893-L932 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.formatAutocompleteResponse | public function formatAutocompleteResponse($results)
{
$output = [];
foreach ($results as $row) {
// Only keep the id and title fields
$item = new stdClass;
$item->id = $row->getKey();
$item->title = $row->getAdminTitleAttribute();
// Add properties for the columns mentioned in the list view within the
// 'columns' property of this row in the response. Use the same logic
// found in Decoy::renderListColumn();
$item->columns = [];
foreach ($this->columns() as $column) {
if (method_exists($row, $column)) {
$item->columns[$column] = call_user_func([$row, $column]);
} elseif (isset($row->$column)) {
if (is_a($row->$column, 'Carbon\Carbon')) {
$item->columns[$column] = $row->$column->format(FORMAT_DATE);
} else {
$item->columns[$column] = $row->$column;
}
} else {
$item->columns[$column] = null;
}
}
// Add the item to the output
$output[] = $item;
}
return $output;
} | php | public function formatAutocompleteResponse($results)
{
$output = [];
foreach ($results as $row) {
// Only keep the id and title fields
$item = new stdClass;
$item->id = $row->getKey();
$item->title = $row->getAdminTitleAttribute();
// Add properties for the columns mentioned in the list view within the
// 'columns' property of this row in the response. Use the same logic
// found in Decoy::renderListColumn();
$item->columns = [];
foreach ($this->columns() as $column) {
if (method_exists($row, $column)) {
$item->columns[$column] = call_user_func([$row, $column]);
} elseif (isset($row->$column)) {
if (is_a($row->$column, 'Carbon\Carbon')) {
$item->columns[$column] = $row->$column->format(FORMAT_DATE);
} else {
$item->columns[$column] = $row->$column;
}
} else {
$item->columns[$column] = null;
}
}
// Add the item to the output
$output[] = $item;
}
return $output;
} | [
"public",
"function",
"formatAutocompleteResponse",
"(",
"$",
"results",
")",
"{",
"$",
"output",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"results",
"as",
"$",
"row",
")",
"{",
"// Only keep the id and title fields",
"$",
"item",
"=",
"new",
"stdClass",
";"... | Format the results of a query in the format needed for the autocomplete
responses
@param array $results
@return array | [
"Format",
"the",
"results",
"of",
"a",
"query",
"in",
"the",
"format",
"needed",
"for",
"the",
"autocomplete",
"responses"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L941-L974 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.parentRelation | private function parentRelation()
{
if ($this->parent && method_exists($this->parent, $this->parent_to_self)) {
return $this->parent->{$this->parent_to_self}();
}
return false;
} | php | private function parentRelation()
{
if ($this->parent && method_exists($this->parent, $this->parent_to_self)) {
return $this->parent->{$this->parent_to_self}();
}
return false;
} | [
"private",
"function",
"parentRelation",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"parent",
"&&",
"method_exists",
"(",
"$",
"this",
"->",
"parent",
",",
"$",
"this",
"->",
"parent_to_self",
")",
")",
"{",
"return",
"$",
"this",
"->",
"parent",
"->... | Run the parent relationship function for the active model, returning the Relation
object. Returns false if none found.
@return Illuminate\Database\Eloquent\Relations\Relation | false | [
"Run",
"the",
"parent",
"relationship",
"function",
"for",
"the",
"active",
"model",
"returning",
"the",
"Relation",
"object",
".",
"Returns",
"false",
"if",
"none",
"found",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L993-L1000 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.overrideViews | protected function overrideViews()
{
$dir = Str::snake($this->controllerName());
$path = base_path('resources/views/admin/').$dir;
app('view')->prependNamespace('decoy', $path);
} | php | protected function overrideViews()
{
$dir = Str::snake($this->controllerName());
$path = base_path('resources/views/admin/').$dir;
app('view')->prependNamespace('decoy', $path);
} | [
"protected",
"function",
"overrideViews",
"(",
")",
"{",
"$",
"dir",
"=",
"Str",
"::",
"snake",
"(",
"$",
"this",
"->",
"controllerName",
"(",
")",
")",
";",
"$",
"path",
"=",
"base_path",
"(",
"'resources/views/admin/'",
")",
".",
"$",
"dir",
";",
"ap... | Tell Laravel to look for view files within the app admin views so that,
on a controller-level basis, the app can customize elements of an admin
view through it's partials.
@return void | [
"Tell",
"Laravel",
"to",
"look",
"for",
"view",
"files",
"within",
"the",
"app",
"admin",
"views",
"so",
"that",
"on",
"a",
"controller",
"-",
"level",
"basis",
"the",
"app",
"can",
"customize",
"elements",
"of",
"an",
"admin",
"view",
"through",
"it",
"... | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L1009-L1014 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.populateView | protected function populateView($content, $vars = [])
{
// The view
if (is_string($content)) {
$this->layout->content = View::make($content);
} else {
$this->layout->content = $content;
}
// Set vars
$this->layout->title = $this->title();
$this->layout->description = $this->description();
View::share('controller', $this->controller);
// Make sure that the content is a Laravel view before applying vars.
// to it. In the case of the index view, `content` is a Fields\Listing
// instance, not a Laravel view
if (is_a($this->layout->content, 'Illuminate\View\View')) {
$this->layout->content->with($vars);
}
// Return the layout View
return $this->layout;
} | php | protected function populateView($content, $vars = [])
{
// The view
if (is_string($content)) {
$this->layout->content = View::make($content);
} else {
$this->layout->content = $content;
}
// Set vars
$this->layout->title = $this->title();
$this->layout->description = $this->description();
View::share('controller', $this->controller);
// Make sure that the content is a Laravel view before applying vars.
// to it. In the case of the index view, `content` is a Fields\Listing
// instance, not a Laravel view
if (is_a($this->layout->content, 'Illuminate\View\View')) {
$this->layout->content->with($vars);
}
// Return the layout View
return $this->layout;
} | [
"protected",
"function",
"populateView",
"(",
"$",
"content",
",",
"$",
"vars",
"=",
"[",
"]",
")",
"{",
"// The view",
"if",
"(",
"is_string",
"(",
"$",
"content",
")",
")",
"{",
"$",
"this",
"->",
"layout",
"->",
"content",
"=",
"View",
"::",
"make... | Pass controller properties that are used by the layout and views through
to the view layer
@param mixed $content string view name or an HtmlObject / View object
@param array $vars Key value pairs passed to the content view
@return Illuminate\View\View | [
"Pass",
"controller",
"properties",
"that",
"are",
"used",
"by",
"the",
"layout",
"and",
"views",
"through",
"to",
"the",
"view",
"layer"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L1024-L1047 | train |
BKWLD/decoy | classes/Controllers/Base.php | Base.successMessage | protected function successMessage($input = '', $verb = 'saved')
{
// Figure out the title and wrap it in quotes
$title = $input;
if (is_a($input, '\Bkwld\Decoy\Models\Base')) {
$title = $input->getAdminTitleAttribute();
}
if ($title && is_string($title)) {
$title = '"'.$title.'"';
}
// Render the message
$message = __('decoy::base.success_message', ['model' => Str::singular($this->title), 'title' => $title, 'verb' => __("decoy::base.verb.$verb")]);
// Add extra messaging for copies
if ($verb == 'duplicated') {
$url = preg_replace('#/duplicate#', '/edit', Request::url());
$message .= __('decoy::base.success_duplicated', ['url' => $url]);
}
// Add extra messaging if the creation was begun from the localize UI
if ($verb == 'duplicated' && is_a($input, '\Bkwld\Decoy\Models\Base') && !empty($input->locale)) {
$message .= __('decoy::base.success_localized', ['locale' => config('decoy.site.locales')[$input->locale]]);
}
// Return message
return $message;
} | php | protected function successMessage($input = '', $verb = 'saved')
{
// Figure out the title and wrap it in quotes
$title = $input;
if (is_a($input, '\Bkwld\Decoy\Models\Base')) {
$title = $input->getAdminTitleAttribute();
}
if ($title && is_string($title)) {
$title = '"'.$title.'"';
}
// Render the message
$message = __('decoy::base.success_message', ['model' => Str::singular($this->title), 'title' => $title, 'verb' => __("decoy::base.verb.$verb")]);
// Add extra messaging for copies
if ($verb == 'duplicated') {
$url = preg_replace('#/duplicate#', '/edit', Request::url());
$message .= __('decoy::base.success_duplicated', ['url' => $url]);
}
// Add extra messaging if the creation was begun from the localize UI
if ($verb == 'duplicated' && is_a($input, '\Bkwld\Decoy\Models\Base') && !empty($input->locale)) {
$message .= __('decoy::base.success_localized', ['locale' => config('decoy.site.locales')[$input->locale]]);
}
// Return message
return $message;
} | [
"protected",
"function",
"successMessage",
"(",
"$",
"input",
"=",
"''",
",",
"$",
"verb",
"=",
"'saved'",
")",
"{",
"// Figure out the title and wrap it in quotes",
"$",
"title",
"=",
"$",
"input",
";",
"if",
"(",
"is_a",
"(",
"$",
"input",
",",
"'\\Bkwld\\... | Creates a success message for CRUD commands
@param Bkwld\Decoy\Model\Base|string $title The model instance that is
being worked on or a string
containing the title
@param string $verb Default: 'saved'. Past tense CRUD verb (created, saved, etc)
@return string The CRUD success message string | [
"Creates",
"a",
"success",
"message",
"for",
"CRUD",
"commands"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Base.php#L1058-L1086 | train |
BKWLD/decoy | classes/Models/Traits/CanSerializeTransform.php | CanSerializeTransform.runSerializeTransforms | public function runSerializeTransforms()
{
// If the class using this trait is a collection, replace the items in the
// collection with the transformed set
if (is_a($this, Collection::class)) {
$this->items = $this->runSerializeTransformsOnCollection($this);
// Otherwise, if the class is a model, act directly on it
} elseif (is_a($this, Model::class)) {
$this->runSerializeTransformsOnModel($this);
}
} | php | public function runSerializeTransforms()
{
// If the class using this trait is a collection, replace the items in the
// collection with the transformed set
if (is_a($this, Collection::class)) {
$this->items = $this->runSerializeTransformsOnCollection($this);
// Otherwise, if the class is a model, act directly on it
} elseif (is_a($this, Model::class)) {
$this->runSerializeTransformsOnModel($this);
}
} | [
"public",
"function",
"runSerializeTransforms",
"(",
")",
"{",
"// If the class using this trait is a collection, replace the items in the",
"// collection with the transformed set",
"if",
"(",
"is_a",
"(",
"$",
"this",
",",
"Collection",
"::",
"class",
")",
")",
"{",
"$",
... | Apply all registered transforms to the items in the collection. If a
transform returns falsey, that model will be removed from the collection
@return void | [
"Apply",
"all",
"registered",
"transforms",
"to",
"the",
"items",
"in",
"the",
"collection",
".",
"If",
"a",
"transform",
"returns",
"falsey",
"that",
"model",
"will",
"be",
"removed",
"from",
"the",
"collection"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Traits/CanSerializeTransform.php#L72-L83 | train |
BKWLD/decoy | classes/Models/Traits/CanSerializeTransform.php | CanSerializeTransform.runSerializeTransformsOnCollection | protected function runSerializeTransformsOnCollection(Collection $collection)
{
// Loop through the collection and transform each model
return $collection->map(function ($item) {
// If collection item isn't a model, don't do anything
if (!is_a($item, Model::class)) return $item;
// Serialize the model
return $this->runSerializeTransformsOnModel($item);
// Remove all the models whose transforms did not return a value. Then
// convert back to an array.
})->filter()->all();
} | php | protected function runSerializeTransformsOnCollection(Collection $collection)
{
// Loop through the collection and transform each model
return $collection->map(function ($item) {
// If collection item isn't a model, don't do anything
if (!is_a($item, Model::class)) return $item;
// Serialize the model
return $this->runSerializeTransformsOnModel($item);
// Remove all the models whose transforms did not return a value. Then
// convert back to an array.
})->filter()->all();
} | [
"protected",
"function",
"runSerializeTransformsOnCollection",
"(",
"Collection",
"$",
"collection",
")",
"{",
"// Loop through the collection and transform each model",
"return",
"$",
"collection",
"->",
"map",
"(",
"function",
"(",
"$",
"item",
")",
"{",
"// If collecti... | Run transforms on every model in a collection
@return Collection | [
"Run",
"transforms",
"on",
"every",
"model",
"in",
"a",
"collection"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Traits/CanSerializeTransform.php#L90-L104 | train |
BKWLD/decoy | classes/Models/Traits/CanSerializeTransform.php | CanSerializeTransform.runSerializeTransformsOnModel | protected function runSerializeTransformsOnModel(Model $model)
{
// Loop through all the transform functions
foreach ($this->serialize_transforms as $transform) {
// Call the transform and if nothing is retuned, return nothing. This will
// be used by runSerializeTransformsOnCollection() to filter out models.
if (!$model = call_user_func($transform, $model)) {
return;
}
}
// Return the transformed model
return $model;
} | php | protected function runSerializeTransformsOnModel(Model $model)
{
// Loop through all the transform functions
foreach ($this->serialize_transforms as $transform) {
// Call the transform and if nothing is retuned, return nothing. This will
// be used by runSerializeTransformsOnCollection() to filter out models.
if (!$model = call_user_func($transform, $model)) {
return;
}
}
// Return the transformed model
return $model;
} | [
"protected",
"function",
"runSerializeTransformsOnModel",
"(",
"Model",
"$",
"model",
")",
"{",
"// Loop through all the transform functions",
"foreach",
"(",
"$",
"this",
"->",
"serialize_transforms",
"as",
"$",
"transform",
")",
"{",
"// Call the transform and if nothing ... | Run transforms on a single model
@param Model $model
@return Model|void | [
"Run",
"transforms",
"on",
"a",
"single",
"model"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Traits/CanSerializeTransform.php#L112-L126 | train |
BKWLD/decoy | classes/Fields/Traits/CaptureLabel.php | CaptureLabel.label | public function label($text, $attributes = [])
{
$this->label_text = $text;
return parent::label($text, $attributes);
} | php | public function label($text, $attributes = [])
{
$this->label_text = $text;
return parent::label($text, $attributes);
} | [
"public",
"function",
"label",
"(",
"$",
"text",
",",
"$",
"attributes",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"label_text",
"=",
"$",
"text",
";",
"return",
"parent",
"::",
"label",
"(",
"$",
"text",
",",
"$",
"attributes",
")",
";",
"}"
] | Override the parent label so we can use the raw text of the label
@param string $text A label
@param array $attributes The label's attributes
@return Field A field | [
"Override",
"the",
"parent",
"label",
"so",
"we",
"can",
"use",
"the",
"raw",
"text",
"of",
"the",
"label"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Fields/Traits/CaptureLabel.php#L25-L30 | train |
BKWLD/decoy | classes/Controllers/ForgotPassword.php | ForgotPassword.showLinkRequestForm | public function showLinkRequestForm()
{
// Pass validation rules
Former::withRules([
'email' => 'required|email',
]);
// Set the breadcrumbs
app('decoy.breadcrumbs')->set([
route('decoy::account@login') => 'Login',
url()->current() => 'Forgot Password',
]);
// Show the page
$this->title = 'Forgot Password';
$this->description = 'You know the drill.';
return $this->populateView('decoy::account.forgot');
} | php | public function showLinkRequestForm()
{
// Pass validation rules
Former::withRules([
'email' => 'required|email',
]);
// Set the breadcrumbs
app('decoy.breadcrumbs')->set([
route('decoy::account@login') => 'Login',
url()->current() => 'Forgot Password',
]);
// Show the page
$this->title = 'Forgot Password';
$this->description = 'You know the drill.';
return $this->populateView('decoy::account.forgot');
} | [
"public",
"function",
"showLinkRequestForm",
"(",
")",
"{",
"// Pass validation rules",
"Former",
"::",
"withRules",
"(",
"[",
"'email'",
"=>",
"'required|email'",
",",
"]",
")",
";",
"// Set the breadcrumbs",
"app",
"(",
"'decoy.breadcrumbs'",
")",
"->",
"set",
"... | Display the form to request a password reset link.
@return \Illuminate\Http\Response | [
"Display",
"the",
"form",
"to",
"request",
"a",
"password",
"reset",
"link",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/ForgotPassword.php#L23-L41 | train |
BKWLD/decoy | classes/Fields/Checklist.php | Checklist.from | public function from(array $options)
{
// Makes the options passed in override anything from the populator.
$this->grouped = true;
// Produce Former-style checkbox options
$options = FormerUtils::checkboxArray($this->name, $options);
$this->checkboxes($options);
// Make chainable
return $this;
} | php | public function from(array $options)
{
// Makes the options passed in override anything from the populator.
$this->grouped = true;
// Produce Former-style checkbox options
$options = FormerUtils::checkboxArray($this->name, $options);
$this->checkboxes($options);
// Make chainable
return $this;
} | [
"public",
"function",
"from",
"(",
"array",
"$",
"options",
")",
"{",
"// Makes the options passed in override anything from the populator.",
"$",
"this",
"->",
"grouped",
"=",
"true",
";",
"// Produce Former-style checkbox options",
"$",
"options",
"=",
"FormerUtils",
":... | Accept checkbox configuration from an associative array
@param array $options
@return $this | [
"Accept",
"checkbox",
"configuration",
"from",
"an",
"associative",
"array"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Fields/Checklist.php#L40-L51 | train |
BKWLD/decoy | classes/Controllers/Elements.php | Elements.index | public function index($locale = null, $tab = null)
{
// If there are no locales, treat the first argument as the tab
if (!($locales = Config::get('decoy.site.locales')) || empty($locales)) {
$tab = $locale;
$locale = null;
// Otherwise, set a default locale if none was specified
} elseif (!$locale) {
$locale = Decoy::defaultLocale();
}
// Get all the elements for the current locale
$elements = app('decoy.elements')->localize($locale)->hydrate(true);
// If the user has customized permissions, filter the elements to only the
// allowed pages of elements.
if ($permissions = app('decoy.user')->getPermissionsAttribute()) {
$elements->onlyPages($permissions->elements);
}
// If handling a deep link to a tab, verify that the passed tab
// slug is a real key in the data. Else 404.
if ($tab && !in_array($tab, $elements->pluck('page_label')
->map(function ($title) {
return Str::slug($title);
})
->all())) {
App::abort(404);
}
// Populate form
Former::withRules($elements->rules());
Former::populate($elements->populate());
// Convert the collection to models for simpler manipulation
$elements = $elements->asModels();
// Set the breadcrumbs NOT include the locale/tab
app('decoy.breadcrumbs')->set([
route('decoy::elements') => $this->title,
]);
// Render the view
return $this->populateView('decoy::elements.index', [
'elements' => $elements,
'locale' => $locale,
'tab' => $tab,
]);
} | php | public function index($locale = null, $tab = null)
{
// If there are no locales, treat the first argument as the tab
if (!($locales = Config::get('decoy.site.locales')) || empty($locales)) {
$tab = $locale;
$locale = null;
// Otherwise, set a default locale if none was specified
} elseif (!$locale) {
$locale = Decoy::defaultLocale();
}
// Get all the elements for the current locale
$elements = app('decoy.elements')->localize($locale)->hydrate(true);
// If the user has customized permissions, filter the elements to only the
// allowed pages of elements.
if ($permissions = app('decoy.user')->getPermissionsAttribute()) {
$elements->onlyPages($permissions->elements);
}
// If handling a deep link to a tab, verify that the passed tab
// slug is a real key in the data. Else 404.
if ($tab && !in_array($tab, $elements->pluck('page_label')
->map(function ($title) {
return Str::slug($title);
})
->all())) {
App::abort(404);
}
// Populate form
Former::withRules($elements->rules());
Former::populate($elements->populate());
// Convert the collection to models for simpler manipulation
$elements = $elements->asModels();
// Set the breadcrumbs NOT include the locale/tab
app('decoy.breadcrumbs')->set([
route('decoy::elements') => $this->title,
]);
// Render the view
return $this->populateView('decoy::elements.index', [
'elements' => $elements,
'locale' => $locale,
'tab' => $tab,
]);
} | [
"public",
"function",
"index",
"(",
"$",
"locale",
"=",
"null",
",",
"$",
"tab",
"=",
"null",
")",
"{",
"// If there are no locales, treat the first argument as the tab",
"if",
"(",
"!",
"(",
"$",
"locales",
"=",
"Config",
"::",
"get",
"(",
"'decoy.site.locales'... | All elements view
@param string $locale The locale to load from the DB
@param string $tab A deep link to a specific tab. Will get processed by JS
@return Illuminate\Http\Response | [
"All",
"elements",
"view"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Elements.php#L42-L91 | train |
BKWLD/decoy | classes/Controllers/Elements.php | Elements.renderField | public static function renderField($el, $key = null)
{
if (!$key) {
$key = $el->inputName();
}
$id = str_replace('|', '-', $key);
switch ($el->type) {
case 'text':
return Former::text($key, $el->label)
->blockHelp($el->help)
->id($id);
case 'textarea':
return Former::textarea($key, $el->label)
->blockHelp($el->help)
->id($id);
case 'wysiwyg':
return Former::wysiwyg($key, $el->label)
->blockHelp($el->help)
->id($id);
case 'image':
return Former::image($key, $el->label)
->forElement($el)
->id($id);
case 'file':
return Former::upload($key, $el->label)
->blockHelp($el->help)
->id($id);
case 'boolean':
return Former::checkbox($key, false)
->checkboxes([
"<b>{$el->label}</b>" => [
'name' => $key,
'value' => 1,
],
])
->blockHelp($el->help)
->id($id)
->push();
case 'select':
return Former::select($key, $el->label)
->options($el->options)
->blockHelp($el->help)
->id($id);
case 'radios':
return Former::radiolist($key, $el->label)
->from($el->options)
->blockHelp($el->help)
->id($id);
case 'checkboxes':
return Former::checklist($key, $el->label)
->from($el->options)
->blockHelp($el->help)
->id($id);
case 'video-encoder':
return Former::videoEncoder($key, $el->label)
->blockHelp($el->help)
->model($el)
->preset($el->preset)
->id($id);
case 'model':
return Former::belongsTo($key, $el->label)
->parent($el->class)
->blockHelp($el->help)
->id($id);
}
} | php | public static function renderField($el, $key = null)
{
if (!$key) {
$key = $el->inputName();
}
$id = str_replace('|', '-', $key);
switch ($el->type) {
case 'text':
return Former::text($key, $el->label)
->blockHelp($el->help)
->id($id);
case 'textarea':
return Former::textarea($key, $el->label)
->blockHelp($el->help)
->id($id);
case 'wysiwyg':
return Former::wysiwyg($key, $el->label)
->blockHelp($el->help)
->id($id);
case 'image':
return Former::image($key, $el->label)
->forElement($el)
->id($id);
case 'file':
return Former::upload($key, $el->label)
->blockHelp($el->help)
->id($id);
case 'boolean':
return Former::checkbox($key, false)
->checkboxes([
"<b>{$el->label}</b>" => [
'name' => $key,
'value' => 1,
],
])
->blockHelp($el->help)
->id($id)
->push();
case 'select':
return Former::select($key, $el->label)
->options($el->options)
->blockHelp($el->help)
->id($id);
case 'radios':
return Former::radiolist($key, $el->label)
->from($el->options)
->blockHelp($el->help)
->id($id);
case 'checkboxes':
return Former::checklist($key, $el->label)
->from($el->options)
->blockHelp($el->help)
->id($id);
case 'video-encoder':
return Former::videoEncoder($key, $el->label)
->blockHelp($el->help)
->model($el)
->preset($el->preset)
->id($id);
case 'model':
return Former::belongsTo($key, $el->label)
->parent($el->class)
->blockHelp($el->help)
->id($id);
}
} | [
"public",
"static",
"function",
"renderField",
"(",
"$",
"el",
",",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"key",
")",
"{",
"$",
"key",
"=",
"$",
"el",
"->",
"inputName",
"(",
")",
";",
"}",
"$",
"id",
"=",
"str_replace",
"(",
... | A helper function for rendering the list of fields
@param Bkwld\Decoy\Models\Element $el
@param string $key
@return Former\Traits\Object | [
"A",
"helper",
"function",
"for",
"rendering",
"the",
"list",
"of",
"fields"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Elements.php#L100-L177 | train |
BKWLD/decoy | classes/Controllers/Elements.php | Elements.store | public function store($locale = null)
{
// Get the default locale
if (!$locale) {
$locale = Decoy::defaultLocale();
}
// Hydrate the elements collection
$elements = app('decoy.elements')
->localize($locale)
->hydrate(true);
// If the user has customized permissions, filter the elements to only the
// allowed pages of elements.
if ($permissions = app('decoy.user')->getPermissionsAttribute()) {
$elements->onlyPages($permissions->elements);
}
// Get all the input such that empty file fields are removed from the input.
$input = Decoy::filteredInput();
// Validate the input
$validator = Validator::make($input, $elements->rules());
if ($validator->fails()) {
throw new ValidationFail($validator);
}
// Merge the input into the elements and save them. Key must be converted back
// from the | delimited format necessitated by PHP
$elements->asModels()->each(function (Element $el) use ($elements, $input) {
// Inform the model as to whether the model already exists in the db.
if ($el->exists = $elements->keyUpdated($el->key)) {
$el->syncOriginal();
}
// Handle images differently, since they get saved in the Images table
if ($el->type == 'image') {
return $this->storeImage($el, $input);
}
// Empty file fields will have no key as a result of the above filtering
$key = $el->inputName();
if (!array_key_exists($key, $input)) {
// If no new video was uploaded but the preset was changed, re-encode
if ($el->type == 'video-encoder' && $el->hasDirtyPreset('value')) {
$el->encode('value', $el->encodingPresetInputVal('value'));
}
return;
}
$value = $input[$key];
// If value is an array, like it would be for the "checkboxes" type, make
// it a comma delimited string
if (is_array($value)) {
$value = implode(',', $value);
}
// We're removing the carriage returns because YAML won't include them and
// all multiline YAML config values were incorrectly being returned as
// dirty.
$value = str_replace("\r", '', $value);
// Check if the model is dirty, manually. Laravel's performInsert()
// doesn't do this, thus we must check ourselves.
if ($value == $el->value) {
return;
}
// If type is a video encoder and the value is empty, delete the row to
// force the encoding row to also delete. This is possible because
// videos cannot have a YAML set default value.
if (!$value && $el->type == 'video-encoder') {
return $el->delete();
}
// Save it
$el->value = Request::hasFile($key) ?
app('upchuck.storage')->moveUpload(Request::file($key)) :
$value;
$el->save();
});
// Clear the cache
$elements->clearCache();
// Redirect back to index
return Redirect::to(URL::current())->with('success',
__('decoy::elements.successfully_saved'));
} | php | public function store($locale = null)
{
// Get the default locale
if (!$locale) {
$locale = Decoy::defaultLocale();
}
// Hydrate the elements collection
$elements = app('decoy.elements')
->localize($locale)
->hydrate(true);
// If the user has customized permissions, filter the elements to only the
// allowed pages of elements.
if ($permissions = app('decoy.user')->getPermissionsAttribute()) {
$elements->onlyPages($permissions->elements);
}
// Get all the input such that empty file fields are removed from the input.
$input = Decoy::filteredInput();
// Validate the input
$validator = Validator::make($input, $elements->rules());
if ($validator->fails()) {
throw new ValidationFail($validator);
}
// Merge the input into the elements and save them. Key must be converted back
// from the | delimited format necessitated by PHP
$elements->asModels()->each(function (Element $el) use ($elements, $input) {
// Inform the model as to whether the model already exists in the db.
if ($el->exists = $elements->keyUpdated($el->key)) {
$el->syncOriginal();
}
// Handle images differently, since they get saved in the Images table
if ($el->type == 'image') {
return $this->storeImage($el, $input);
}
// Empty file fields will have no key as a result of the above filtering
$key = $el->inputName();
if (!array_key_exists($key, $input)) {
// If no new video was uploaded but the preset was changed, re-encode
if ($el->type == 'video-encoder' && $el->hasDirtyPreset('value')) {
$el->encode('value', $el->encodingPresetInputVal('value'));
}
return;
}
$value = $input[$key];
// If value is an array, like it would be for the "checkboxes" type, make
// it a comma delimited string
if (is_array($value)) {
$value = implode(',', $value);
}
// We're removing the carriage returns because YAML won't include them and
// all multiline YAML config values were incorrectly being returned as
// dirty.
$value = str_replace("\r", '', $value);
// Check if the model is dirty, manually. Laravel's performInsert()
// doesn't do this, thus we must check ourselves.
if ($value == $el->value) {
return;
}
// If type is a video encoder and the value is empty, delete the row to
// force the encoding row to also delete. This is possible because
// videos cannot have a YAML set default value.
if (!$value && $el->type == 'video-encoder') {
return $el->delete();
}
// Save it
$el->value = Request::hasFile($key) ?
app('upchuck.storage')->moveUpload(Request::file($key)) :
$value;
$el->save();
});
// Clear the cache
$elements->clearCache();
// Redirect back to index
return Redirect::to(URL::current())->with('success',
__('decoy::elements.successfully_saved'));
} | [
"public",
"function",
"store",
"(",
"$",
"locale",
"=",
"null",
")",
"{",
"// Get the default locale",
"if",
"(",
"!",
"$",
"locale",
")",
"{",
"$",
"locale",
"=",
"Decoy",
"::",
"defaultLocale",
"(",
")",
";",
"}",
"// Hydrate the elements collection",
"$",... | Handle form post
@param string $locale The locale to assign to it
@return Illuminate\Http\Response | [
"Handle",
"form",
"post"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Elements.php#L185-L276 | train |
BKWLD/decoy | classes/Controllers/Elements.php | Elements.storeImage | protected function storeImage(Element $el, $input)
{
// Do nothing if no images
if (!is_array($input['images'])) {
return;
}
// Check for the image in the input. If isn't found, make no changes.
$name = $el->inputName();
if (!$data = array_first($input['images'],
function ($data, $id) use ($name) {
return $data['name'] == $name;
})) {
return;
}
// Update an existing image
if ($image = $el->images->first()) {
$image->fill($data)->save();
// Or create a new image, if file data was supplied
} elseif (!empty($data['file'])) {
$el->value = null;
$el->save();
$image = new Image($data);
$el->images()->save($image);
// Othweise, nothing to do
} else {
return;
}
// Update the element with the path to the image
$el->value = $image->file;
$el->save();
} | php | protected function storeImage(Element $el, $input)
{
// Do nothing if no images
if (!is_array($input['images'])) {
return;
}
// Check for the image in the input. If isn't found, make no changes.
$name = $el->inputName();
if (!$data = array_first($input['images'],
function ($data, $id) use ($name) {
return $data['name'] == $name;
})) {
return;
}
// Update an existing image
if ($image = $el->images->first()) {
$image->fill($data)->save();
// Or create a new image, if file data was supplied
} elseif (!empty($data['file'])) {
$el->value = null;
$el->save();
$image = new Image($data);
$el->images()->save($image);
// Othweise, nothing to do
} else {
return;
}
// Update the element with the path to the image
$el->value = $image->file;
$el->save();
} | [
"protected",
"function",
"storeImage",
"(",
"Element",
"$",
"el",
",",
"$",
"input",
")",
"{",
"// Do nothing if no images",
"if",
"(",
"!",
"is_array",
"(",
"$",
"input",
"[",
"'images'",
"]",
")",
")",
"{",
"return",
";",
"}",
"// Check for the image in th... | Handle storage of image Element types
@param Element $el
@param array $input
@return void | [
"Handle",
"storage",
"of",
"image",
"Element",
"types"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Elements.php#L285-L320 | train |
BKWLD/decoy | classes/Controllers/Elements.php | Elements.field | public function field($key)
{
return View::make('decoy::layouts.blank')
->nest('content', 'decoy::elements.field', [
'element' => app('decoy.elements')
->localize(Decoy::locale())
->hydrate(true)
->get($key),
]);
} | php | public function field($key)
{
return View::make('decoy::layouts.blank')
->nest('content', 'decoy::elements.field', [
'element' => app('decoy.elements')
->localize(Decoy::locale())
->hydrate(true)
->get($key),
]);
} | [
"public",
"function",
"field",
"(",
"$",
"key",
")",
"{",
"return",
"View",
"::",
"make",
"(",
"'decoy::layouts.blank'",
")",
"->",
"nest",
"(",
"'content'",
",",
"'decoy::elements.field'",
",",
"[",
"'element'",
"=>",
"app",
"(",
"'decoy.elements'",
")",
"-... | Show the field editor form that will appear in an iframe on
the frontend
@param string $key A full Element key
@return Illuminate\Http\Response | [
"Show",
"the",
"field",
"editor",
"form",
"that",
"will",
"appear",
"in",
"an",
"iframe",
"on",
"the",
"frontend"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Elements.php#L329-L338 | train |
BKWLD/decoy | classes/Controllers/Elements.php | Elements.fieldUpdate | public function fieldUpdate($key)
{
$elements = app('decoy.elements')->localize(Decoy::locale());
// If the value has changed, update or an insert a record in the database.
$el = Decoy::el($key);
$value = request('value');
if ($value != $el->value || Request::hasFile('value')) {
// Making use of the model's exists property to trigger Laravel's
// internal logic.
$el->exists = $elements->keyUpdated($el->key);
// Save it. Files will be automatically attached via model callbacks
$el->value = $value;
$el->locale = Decoy::locale();
$el->save();
// Clear the cache
$elements->clearCache();
}
// Return the layout with JUST a script variable with the element value
// after saving. Thus, post any saving callback operations.
return View::make('decoy::layouts.blank', [
'content' => "<div id='response' data-key='{$key}'>{$el}</div>"
]);
} | php | public function fieldUpdate($key)
{
$elements = app('decoy.elements')->localize(Decoy::locale());
// If the value has changed, update or an insert a record in the database.
$el = Decoy::el($key);
$value = request('value');
if ($value != $el->value || Request::hasFile('value')) {
// Making use of the model's exists property to trigger Laravel's
// internal logic.
$el->exists = $elements->keyUpdated($el->key);
// Save it. Files will be automatically attached via model callbacks
$el->value = $value;
$el->locale = Decoy::locale();
$el->save();
// Clear the cache
$elements->clearCache();
}
// Return the layout with JUST a script variable with the element value
// after saving. Thus, post any saving callback operations.
return View::make('decoy::layouts.blank', [
'content' => "<div id='response' data-key='{$key}'>{$el}</div>"
]);
} | [
"public",
"function",
"fieldUpdate",
"(",
"$",
"key",
")",
"{",
"$",
"elements",
"=",
"app",
"(",
"'decoy.elements'",
")",
"->",
"localize",
"(",
"Decoy",
"::",
"locale",
"(",
")",
")",
";",
"// If the value has changed, update or an insert a record in the database.... | Update a single field because of a frontend Element editor
iframe post
@param string $key A full Element key
@return Illuminate\Http\Response | [
"Update",
"a",
"single",
"field",
"because",
"of",
"a",
"frontend",
"Element",
"editor",
"iframe",
"post"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Elements.php#L347-L374 | train |
BKWLD/decoy | classes/Controllers/Elements.php | Elements.getPermissionOptions | public function getPermissionOptions()
{
// Get all the grouped elements
$elements = app('decoy.elements')
->localize(Decoy::locale())
->hydrate(true)
->asModels()
->sortBy('page_label')
->groupBy('page_label');
// Map to the expected permisions forat
$out = [];
foreach ($elements as $page_label => $fields) {
$out[Str::slug($page_label)] = [$page_label, $fields[0]->page_help];
}
return $out;
} | php | public function getPermissionOptions()
{
// Get all the grouped elements
$elements = app('decoy.elements')
->localize(Decoy::locale())
->hydrate(true)
->asModels()
->sortBy('page_label')
->groupBy('page_label');
// Map to the expected permisions forat
$out = [];
foreach ($elements as $page_label => $fields) {
$out[Str::slug($page_label)] = [$page_label, $fields[0]->page_help];
}
return $out;
} | [
"public",
"function",
"getPermissionOptions",
"(",
")",
"{",
"// Get all the grouped elements",
"$",
"elements",
"=",
"app",
"(",
"'decoy.elements'",
")",
"->",
"localize",
"(",
"Decoy",
"::",
"locale",
"(",
")",
")",
"->",
"hydrate",
"(",
"true",
")",
"->",
... | The permissions options are a list of all the tabs
@return array | [
"The",
"permissions",
"options",
"are",
"a",
"list",
"of",
"all",
"the",
"tabs"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Controllers/Elements.php#L381-L398 | train |
BKWLD/decoy | classes/Helpers.php | Helpers.title | public function title()
{
// If no title has been set, try to figure it out based on breadcrumbs
$title = View::yieldContent('title');
if (empty($title)) {
$title = app('decoy.breadcrumbs')->title();
}
// Set the title
$site = $this->site();
return '<title>' . ($title ? "$title | $site" : $site) . '</title>';
} | php | public function title()
{
// If no title has been set, try to figure it out based on breadcrumbs
$title = View::yieldContent('title');
if (empty($title)) {
$title = app('decoy.breadcrumbs')->title();
}
// Set the title
$site = $this->site();
return '<title>' . ($title ? "$title | $site" : $site) . '</title>';
} | [
"public",
"function",
"title",
"(",
")",
"{",
"// If no title has been set, try to figure it out based on breadcrumbs",
"$",
"title",
"=",
"View",
"::",
"yieldContent",
"(",
"'title'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"title",
")",
")",
"{",
"$",
"title",... | Generate title tags based on section content
@return string | [
"Generate",
"title",
"tags",
"based",
"on",
"section",
"content"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Helpers.php#L32-L44 | train |
BKWLD/decoy | classes/Helpers.php | Helpers.site | public function site()
{
$site = Config::get('decoy.site.name');
if (is_callable($site)) {
$site = call_user_func($site);
}
return $site;
} | php | public function site()
{
$site = Config::get('decoy.site.name');
if (is_callable($site)) {
$site = call_user_func($site);
}
return $site;
} | [
"public",
"function",
"site",
"(",
")",
"{",
"$",
"site",
"=",
"Config",
"::",
"get",
"(",
"'decoy.site.name'",
")",
";",
"if",
"(",
"is_callable",
"(",
"$",
"site",
")",
")",
"{",
"$",
"site",
"=",
"call_user_func",
"(",
"$",
"site",
")",
";",
"}"... | Get the site name
@return string | [
"Get",
"the",
"site",
"name"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Helpers.php#L51-L59 | train |
BKWLD/decoy | classes/Helpers.php | Helpers.bodyClass | public function bodyClass()
{
$path = Request::path();
$classes = [];
// Special condition for the elements
if (strpos($path, '/elements/field/') !== false) {
return 'elements field';
}
// Special condition for the reset page, which passes the token in as part of the route
if (strpos($path, '/reset/') !== false) {
return 'login reset';
}
// Tab-sidebar views support deep links that would normally affect the
// class of the page.
if (strpos($path, '/elements/') !== false) {
return 'elements index';
}
// Get the controller and action from the URL
preg_match('#/([a-z-]+)(?:/\d+)?(?:/(create|edit))?$#i', $path, $matches);
$controller = empty($matches[1]) ? 'login' : $matches[1];
$action = empty($matches[2]) ? 'index' : $matches[2];
array_push($classes, $controller, $action);
// Add the admin roles
if ($admin = app('decoy.user')) {
$classes[] = 'role-'.$admin->role;
}
// Return the list of classes
return implode(' ', $classes);
} | php | public function bodyClass()
{
$path = Request::path();
$classes = [];
// Special condition for the elements
if (strpos($path, '/elements/field/') !== false) {
return 'elements field';
}
// Special condition for the reset page, which passes the token in as part of the route
if (strpos($path, '/reset/') !== false) {
return 'login reset';
}
// Tab-sidebar views support deep links that would normally affect the
// class of the page.
if (strpos($path, '/elements/') !== false) {
return 'elements index';
}
// Get the controller and action from the URL
preg_match('#/([a-z-]+)(?:/\d+)?(?:/(create|edit))?$#i', $path, $matches);
$controller = empty($matches[1]) ? 'login' : $matches[1];
$action = empty($matches[2]) ? 'index' : $matches[2];
array_push($classes, $controller, $action);
// Add the admin roles
if ($admin = app('decoy.user')) {
$classes[] = 'role-'.$admin->role;
}
// Return the list of classes
return implode(' ', $classes);
} | [
"public",
"function",
"bodyClass",
"(",
")",
"{",
"$",
"path",
"=",
"Request",
"::",
"path",
"(",
")",
";",
"$",
"classes",
"=",
"[",
"]",
";",
"// Special condition for the elements",
"if",
"(",
"strpos",
"(",
"$",
"path",
",",
"'/elements/field/'",
")",
... | Add the controller and action as CSS classes on the body tag | [
"Add",
"the",
"controller",
"and",
"action",
"as",
"CSS",
"classes",
"on",
"the",
"body",
"tag"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Helpers.php#L64-L98 | train |
BKWLD/decoy | classes/Helpers.php | Helpers.els | public function els($prefix, $crops = [])
{
return app('decoy.elements')
->localize($this->locale())
->getMany($prefix, $crops);
} | php | public function els($prefix, $crops = [])
{
return app('decoy.elements')
->localize($this->locale())
->getMany($prefix, $crops);
} | [
"public",
"function",
"els",
"(",
"$",
"prefix",
",",
"$",
"crops",
"=",
"[",
"]",
")",
"{",
"return",
"app",
"(",
"'decoy.elements'",
")",
"->",
"localize",
"(",
"$",
"this",
"->",
"locale",
"(",
")",
")",
"->",
"getMany",
"(",
"$",
"prefix",
",",... | Return a number of Element values at once in an associative array
@param string $prefix Any leading part of a key
@param array $crops Assoc array with Element partial keys for ITS keys
and values as an arary of crop()-style arguments
@return array | [
"Return",
"a",
"number",
"of",
"Element",
"values",
"at",
"once",
"in",
"an",
"associative",
"array"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Helpers.php#L221-L226 | train |
BKWLD/decoy | classes/Helpers.php | Helpers.defaultLocale | public function defaultLocale()
{
if (($locales = Config::get('decoy.site.locales'))
&& is_array($locales)) {
reset($locales);
return key($locales);
}
} | php | public function defaultLocale()
{
if (($locales = Config::get('decoy.site.locales'))
&& is_array($locales)) {
reset($locales);
return key($locales);
}
} | [
"public",
"function",
"defaultLocale",
"(",
")",
"{",
"if",
"(",
"(",
"$",
"locales",
"=",
"Config",
"::",
"get",
"(",
"'decoy.site.locales'",
")",
")",
"&&",
"is_array",
"(",
"$",
"locales",
")",
")",
"{",
"reset",
"(",
"$",
"locales",
")",
";",
"re... | Get the default locale, aka, the first locales array key
@return string | [
"Get",
"the",
"default",
"locale",
"aka",
"the",
"first",
"locales",
"array",
"key"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Helpers.php#L304-L312 | train |
BKWLD/decoy | classes/Helpers.php | Helpers.modelForController | public function modelForController($controller)
{
// Swap out the namespace if decoy
$model = str_replace('Bkwld\Decoy\Controllers',
'Bkwld\Decoy\Models',
$controller,
$is_decoy);
// Replace non-decoy controller's with the standard model namespace
if (!$is_decoy) {
$namespace = ucfirst(Config::get('decoy.core.dir'));
$model = str_replace('App\Http\Controllers\\'.$namespace.'\\', 'App\\', $model);
}
// Make it singular
$offset = strrpos($model, '\\') + 1;
return substr($model, 0, $offset).Str::singular(substr($model, $offset));
} | php | public function modelForController($controller)
{
// Swap out the namespace if decoy
$model = str_replace('Bkwld\Decoy\Controllers',
'Bkwld\Decoy\Models',
$controller,
$is_decoy);
// Replace non-decoy controller's with the standard model namespace
if (!$is_decoy) {
$namespace = ucfirst(Config::get('decoy.core.dir'));
$model = str_replace('App\Http\Controllers\\'.$namespace.'\\', 'App\\', $model);
}
// Make it singular
$offset = strrpos($model, '\\') + 1;
return substr($model, 0, $offset).Str::singular(substr($model, $offset));
} | [
"public",
"function",
"modelForController",
"(",
"$",
"controller",
")",
"{",
"// Swap out the namespace if decoy",
"$",
"model",
"=",
"str_replace",
"(",
"'Bkwld\\Decoy\\Controllers'",
",",
"'Bkwld\\Decoy\\Models'",
",",
"$",
"controller",
",",
"$",
"is_decoy",
")",
... | Get the model class string from a controller class string
@param string $controller ex: "App\Http\Controllers\Admin\People"
@return string ex: "App\Person" | [
"Get",
"the",
"model",
"class",
"string",
"from",
"a",
"controller",
"class",
"string"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Helpers.php#L320-L338 | train |
BKWLD/decoy | classes/Helpers.php | Helpers.controllerForModel | public function controllerForModel($model)
{
// Swap out the namespace if decoy
$controller = str_replace('Bkwld\Decoy\Models', 'Bkwld\Decoy\Controllers', $model, $is_decoy);
// Replace non-decoy controller's with the standard model namespace
if (!$is_decoy) {
$namespace = ucfirst(Config::get('decoy.core.dir'));
$controller = str_replace('App\\', 'App\Http\Controllers\\'.$namespace.'\\', $controller);
}
// Make it plural
$offset = strrpos($controller, '\\') + 1;
return substr($controller, 0, $offset).Str::plural(substr($controller, $offset));
} | php | public function controllerForModel($model)
{
// Swap out the namespace if decoy
$controller = str_replace('Bkwld\Decoy\Models', 'Bkwld\Decoy\Controllers', $model, $is_decoy);
// Replace non-decoy controller's with the standard model namespace
if (!$is_decoy) {
$namespace = ucfirst(Config::get('decoy.core.dir'));
$controller = str_replace('App\\', 'App\Http\Controllers\\'.$namespace.'\\', $controller);
}
// Make it plural
$offset = strrpos($controller, '\\') + 1;
return substr($controller, 0, $offset).Str::plural(substr($controller, $offset));
} | [
"public",
"function",
"controllerForModel",
"(",
"$",
"model",
")",
"{",
"// Swap out the namespace if decoy",
"$",
"controller",
"=",
"str_replace",
"(",
"'Bkwld\\Decoy\\Models'",
",",
"'Bkwld\\Decoy\\Controllers'",
",",
"$",
"model",
",",
"$",
"is_decoy",
")",
";",
... | Get the controller class string from a model class string
@param string $controller ex: "App\Person"
@return string ex: "App\Http\Controllers\Admin\People" | [
"Get",
"the",
"controller",
"class",
"string",
"from",
"a",
"model",
"class",
"string"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Helpers.php#L346-L360 | train |
BKWLD/decoy | classes/Helpers.php | Helpers.filteredInput | public function filteredInput()
{
$files = $this->arrayFilterRecursive(Request::file());
$input = array_replace_recursive(Request::input(), $files);
return Library\Utils\Collection::nullEmpties($input);
} | php | public function filteredInput()
{
$files = $this->arrayFilterRecursive(Request::file());
$input = array_replace_recursive(Request::input(), $files);
return Library\Utils\Collection::nullEmpties($input);
} | [
"public",
"function",
"filteredInput",
"(",
")",
"{",
"$",
"files",
"=",
"$",
"this",
"->",
"arrayFilterRecursive",
"(",
"Request",
"::",
"file",
"(",
")",
")",
";",
"$",
"input",
"=",
"array_replace_recursive",
"(",
"Request",
"::",
"input",
"(",
")",
"... | Get all input but filter out empty file fields. This prevents empty file
fields from overriding existing files on a model. Using this assumes that
we are filling a model and then validating the model attributes.
@return array | [
"Get",
"all",
"input",
"but",
"filter",
"out",
"empty",
"file",
"fields",
".",
"This",
"prevents",
"empty",
"file",
"fields",
"from",
"overriding",
"existing",
"files",
"on",
"a",
"model",
".",
"Using",
"this",
"assumes",
"that",
"we",
"are",
"filling",
"a... | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Helpers.php#L393-L399 | train |
BKWLD/decoy | classes/Observers/ModelCallbacks.php | ModelCallbacks.handle | public function handle($event, $payload)
{
list($model) = $payload;
// Get the action from the event name
preg_match('#\.(\w+)#', $event, $matches);
$action = $matches[1];
// If there is matching callback method on the model, call it, passing
// any additional event arguments to it
$method = 'on'.Str::studly($action);
if (method_exists($model, $method)) {
return call_user_func_array([$model, $method], array_slice($payload, 1));
}
} | php | public function handle($event, $payload)
{
list($model) = $payload;
// Get the action from the event name
preg_match('#\.(\w+)#', $event, $matches);
$action = $matches[1];
// If there is matching callback method on the model, call it, passing
// any additional event arguments to it
$method = 'on'.Str::studly($action);
if (method_exists($model, $method)) {
return call_user_func_array([$model, $method], array_slice($payload, 1));
}
} | [
"public",
"function",
"handle",
"(",
"$",
"event",
",",
"$",
"payload",
")",
"{",
"list",
"(",
"$",
"model",
")",
"=",
"$",
"payload",
";",
"// Get the action from the event name",
"preg_match",
"(",
"'#\\.(\\w+)#'",
",",
"$",
"event",
",",
"$",
"matches",
... | Handle all model events, both Eloquent and Decoy
@param string $event
@param array $payload Contains:
- Bkwld\Decoy\Models\Base $model
@return void | [
"Handle",
"all",
"model",
"events",
"both",
"Eloquent",
"and",
"Decoy"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Observers/ModelCallbacks.php#L22-L36 | train |
BKWLD/decoy | classes/Models/Element.php | Element.setAttribute | public function setAttribute($key, $value)
{
if ($key == 'type') {
switch ($value) {
case 'image': self::$rules['value'] = 'image';
break;
case 'file': self::$rules['value'] = 'file';
break;
case 'video-encoder': self::$rules['value'] = 'video';
break;
}
}
// Continue
return parent::setAttribute($key, $value);
} | php | public function setAttribute($key, $value)
{
if ($key == 'type') {
switch ($value) {
case 'image': self::$rules['value'] = 'image';
break;
case 'file': self::$rules['value'] = 'file';
break;
case 'video-encoder': self::$rules['value'] = 'video';
break;
}
}
// Continue
return parent::setAttribute($key, $value);
} | [
"public",
"function",
"setAttribute",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"key",
"==",
"'type'",
")",
"{",
"switch",
"(",
"$",
"value",
")",
"{",
"case",
"'image'",
":",
"self",
"::",
"$",
"rules",
"[",
"'value'",
"]",
"... | Subclass setAttribute so that we can automatically set validation
rules based on the Element type
@param string $key
@param mixed $value
@return void | [
"Subclass",
"setAttribute",
"so",
"that",
"we",
"can",
"automatically",
"set",
"validation",
"rules",
"based",
"on",
"the",
"Element",
"type"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Element.php#L103-L118 | train |
BKWLD/decoy | classes/Models/Element.php | Element.value | public function value()
{
// Must return a string
if (empty($this->value)) {
return '';
}
// Different outputs depending on type
switch ($this->type) {
case 'boolean': return !empty($this->value);
case 'image': return $this->img()->url;
case 'textarea': return nl2br($this->value);
case 'wysiwyg': return Str::startsWith($this->value, '<') ? $this->value : "<p>{$this->value}</p>";
case 'checkboxes': return explode(',', $this->value);
case 'video-encoder': return $this->encoding('value')->tag;
case 'model': return $this->relatedModel();
default: return $this->value;
}
} | php | public function value()
{
// Must return a string
if (empty($this->value)) {
return '';
}
// Different outputs depending on type
switch ($this->type) {
case 'boolean': return !empty($this->value);
case 'image': return $this->img()->url;
case 'textarea': return nl2br($this->value);
case 'wysiwyg': return Str::startsWith($this->value, '<') ? $this->value : "<p>{$this->value}</p>";
case 'checkboxes': return explode(',', $this->value);
case 'video-encoder': return $this->encoding('value')->tag;
case 'model': return $this->relatedModel();
default: return $this->value;
}
} | [
"public",
"function",
"value",
"(",
")",
"{",
"// Must return a string",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"value",
")",
")",
"{",
"return",
"''",
";",
"}",
"// Different outputs depending on type",
"switch",
"(",
"$",
"this",
"->",
"type",
")",
... | Format the value before returning it based on the type
@return mixed Stringable | [
"Format",
"the",
"value",
"before",
"returning",
"it",
"based",
"on",
"the",
"type"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Element.php#L125-L144 | train |
BKWLD/decoy | classes/Models/Element.php | Element.relatedModel | protected function relatedModel()
{
$yaml = app('decoy.elements')->getConfig();
$model = array_get($yaml, $this->key.'.class')
?: array_get($yaml, $this->key.',model.class');
return $model::find($this->value);
} | php | protected function relatedModel()
{
$yaml = app('decoy.elements')->getConfig();
$model = array_get($yaml, $this->key.'.class')
?: array_get($yaml, $this->key.',model.class');
return $model::find($this->value);
} | [
"protected",
"function",
"relatedModel",
"(",
")",
"{",
"$",
"yaml",
"=",
"app",
"(",
"'decoy.elements'",
")",
"->",
"getConfig",
"(",
")",
";",
"$",
"model",
"=",
"array_get",
"(",
"$",
"yaml",
",",
"$",
"this",
"->",
"key",
".",
"'.class'",
")",
"?... | Get the model referenced in a "model" field
@return Model | [
"Get",
"the",
"model",
"referenced",
"in",
"a",
"model",
"field"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Element.php#L151-L158 | train |
BKWLD/decoy | classes/Models/Element.php | Element.img | public function img()
{
// Check for an existing Image relation
if (($image = $this->parentImg($this->inputName()))
&& $image->exists) {
// If the Image represents a default image, but doesn't match the current
// item from the config, trash the current one and build the new default
// image.
if ($replacement = $this->getReplacementImage($image)) {
return $replacement;
}
// Return the found image
return $image;
}
// Else return a default image
return $this->defaultImage();
} | php | public function img()
{
// Check for an existing Image relation
if (($image = $this->parentImg($this->inputName()))
&& $image->exists) {
// If the Image represents a default image, but doesn't match the current
// item from the config, trash the current one and build the new default
// image.
if ($replacement = $this->getReplacementImage($image)) {
return $replacement;
}
// Return the found image
return $image;
}
// Else return a default image
return $this->defaultImage();
} | [
"public",
"function",
"img",
"(",
")",
"{",
"// Check for an existing Image relation",
"if",
"(",
"(",
"$",
"image",
"=",
"$",
"this",
"->",
"parentImg",
"(",
"$",
"this",
"->",
"inputName",
"(",
")",
")",
")",
"&&",
"$",
"image",
"->",
"exists",
")",
... | Look for default iamges using a named key. It was a lot simpler in the
integeration with the Elements admin UI to store the input name in the
"name" attribute
@return Image | [
"Look",
"for",
"default",
"iamges",
"using",
"a",
"named",
"key",
".",
"It",
"was",
"a",
"lot",
"simpler",
"in",
"the",
"integeration",
"with",
"the",
"Elements",
"admin",
"UI",
"to",
"store",
"the",
"input",
"name",
"in",
"the",
"name",
"attribute"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Element.php#L189-L208 | train |
BKWLD/decoy | classes/Models/Element.php | Element.getReplacementImage | protected function getReplacementImage(Image $image)
{
// Check that the image is in the elements dir, which means it's
// a default image
if (!strpos($image->file, '/elements/')) {
return;
}
// Get the current file value form the YAML. Need to check for the
// shorthand with the type suffix as well.
$yaml = app('decoy.elements')->assocConfig();
$replacement = $yaml[$this->key]['value'];
// Check if the filenames are the same
if (pathinfo($image->file, PATHINFO_BASENAME)
== pathinfo($replacement, PATHINFO_BASENAME)) {
return;
}
// Since the filenames are not the same, remove the old image and generate
// a new one
$image->delete();
$this->exists = true; // It actually does exist if there was an Image
$this->value = $replacement;
return $this->defaultImage();
} | php | protected function getReplacementImage(Image $image)
{
// Check that the image is in the elements dir, which means it's
// a default image
if (!strpos($image->file, '/elements/')) {
return;
}
// Get the current file value form the YAML. Need to check for the
// shorthand with the type suffix as well.
$yaml = app('decoy.elements')->assocConfig();
$replacement = $yaml[$this->key]['value'];
// Check if the filenames are the same
if (pathinfo($image->file, PATHINFO_BASENAME)
== pathinfo($replacement, PATHINFO_BASENAME)) {
return;
}
// Since the filenames are not the same, remove the old image and generate
// a new one
$image->delete();
$this->exists = true; // It actually does exist if there was an Image
$this->value = $replacement;
return $this->defaultImage();
} | [
"protected",
"function",
"getReplacementImage",
"(",
"Image",
"$",
"image",
")",
"{",
"// Check that the image is in the elements dir, which means it's",
"// a default image",
"if",
"(",
"!",
"strpos",
"(",
"$",
"image",
"->",
"file",
",",
"'/elements/'",
")",
")",
"{... | Check if the Image represents a default image but is out of date
@param Image $image
@return Image|void | [
"Check",
"if",
"the",
"Image",
"represents",
"a",
"default",
"image",
"but",
"is",
"out",
"of",
"date"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Element.php#L216-L242 | train |
BKWLD/decoy | classes/Models/Element.php | Element.defaultImage | public function defaultImage()
{
// Return an empty Image object if no default value
if (empty($this->value)) {
return new Image;
}
// All src images must live in the /img (relative) directory
if (!Str::is('/img/*', $this->value)) {
$msg = 'Element images must be stored in public/img: '.$this->value;
throw new Exception($msg);
}
// Check if the image already exists in the uploads directory
$src = $this->value;
$src_abs = public_path($src);
$path = str_replace('/img/', '/elements/', $src);
if (!app('upchuck.disk')->has($path)) {
// Copy it to the disk
$stream = fopen($src_abs, 'r+');
app('upchuck.disk')->writeStream($path, $stream);
fclose($stream);
}
// Wrap the touching of the element and images table in a transaction
// so that the element isn't updated if the images write fails
DB::beginTransaction();
// Update or create this Element instance
$this->value = app('upchuck')->url($path);
$this->save();
// Create and return new Image instance. The Image::populateFileMeta()
// requires an UploadedFile, so we need to do it manually here.
$size = getimagesize($src_abs);
$image = new Image([
'file' => $this->value,
'name' => $this->inputName(),
'file_type' => pathinfo($src_abs, PATHINFO_EXTENSION),
'file_size' => filesize($src_abs),
'width' => $size[0],
'height' => $size[1],
]);
$this->images()->save($image);
DB::commit();
// Clear cached image relations
unset($this->relations['images']);
// Return the image
return $image;
} | php | public function defaultImage()
{
// Return an empty Image object if no default value
if (empty($this->value)) {
return new Image;
}
// All src images must live in the /img (relative) directory
if (!Str::is('/img/*', $this->value)) {
$msg = 'Element images must be stored in public/img: '.$this->value;
throw new Exception($msg);
}
// Check if the image already exists in the uploads directory
$src = $this->value;
$src_abs = public_path($src);
$path = str_replace('/img/', '/elements/', $src);
if (!app('upchuck.disk')->has($path)) {
// Copy it to the disk
$stream = fopen($src_abs, 'r+');
app('upchuck.disk')->writeStream($path, $stream);
fclose($stream);
}
// Wrap the touching of the element and images table in a transaction
// so that the element isn't updated if the images write fails
DB::beginTransaction();
// Update or create this Element instance
$this->value = app('upchuck')->url($path);
$this->save();
// Create and return new Image instance. The Image::populateFileMeta()
// requires an UploadedFile, so we need to do it manually here.
$size = getimagesize($src_abs);
$image = new Image([
'file' => $this->value,
'name' => $this->inputName(),
'file_type' => pathinfo($src_abs, PATHINFO_EXTENSION),
'file_size' => filesize($src_abs),
'width' => $size[0],
'height' => $size[1],
]);
$this->images()->save($image);
DB::commit();
// Clear cached image relations
unset($this->relations['images']);
// Return the image
return $image;
} | [
"public",
"function",
"defaultImage",
"(",
")",
"{",
"// Return an empty Image object if no default value",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"value",
")",
")",
"{",
"return",
"new",
"Image",
";",
"}",
"// All src images must live in the /img (relative) direct... | Check if the value looks like an image. If it does, copy it to the uploads
dir so Croppa can work on it and return the modified path
@return Image | [
"Check",
"if",
"the",
"value",
"looks",
"like",
"an",
"image",
".",
"If",
"it",
"does",
"copy",
"it",
"to",
"the",
"uploads",
"dir",
"so",
"Croppa",
"can",
"work",
"on",
"it",
"and",
"return",
"the",
"modified",
"path"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Element.php#L250-L302 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.asModels | public function asModels()
{
$this->hydrate();
return new ModelCollection(array_map(function ($element, $key) {
// Add the key as an attribute
return new $this->model(array_merge($element, ['key' => $key]));
}, $this->all(), array_keys($this->items)));
} | php | public function asModels()
{
$this->hydrate();
return new ModelCollection(array_map(function ($element, $key) {
// Add the key as an attribute
return new $this->model(array_merge($element, ['key' => $key]));
}, $this->all(), array_keys($this->items)));
} | [
"public",
"function",
"asModels",
"(",
")",
"{",
"$",
"this",
"->",
"hydrate",
"(",
")",
";",
"return",
"new",
"ModelCollection",
"(",
"array_map",
"(",
"function",
"(",
"$",
"element",
",",
"$",
"key",
")",
"{",
"// Add the key as an attribute",
"return",
... | Map the items into a collection of Element instances
@return Bkwld\Decoy\Collections\Elements | [
"Map",
"the",
"items",
"into",
"a",
"collection",
"of",
"Element",
"instances"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L71-L80 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.get | public function get($key, $default = null)
{
$this->hydrate();
// Create an Element instance using the data for the key
if ($this->has($key)) {
return new $this->model(array_merge($this->items[$key], ['key' => $key]));
}
// If the key doesn't exist but a default was passed in, return it
if ($default) {
return $default;
}
// if the key doesn't exist, but running locally, throw an exception
if (App::isLocal()) {
throw new Exception("Element key '{$key}' is not declared in elements.yaml.");
}
// Otherwise, like if key doesn't exist and running on production,
// return an empty Element, whose ->toString() will return an empty string.
Log::error("Element key '{$key}' is not declared in elements.yaml.");
return new $this->model();
} | php | public function get($key, $default = null)
{
$this->hydrate();
// Create an Element instance using the data for the key
if ($this->has($key)) {
return new $this->model(array_merge($this->items[$key], ['key' => $key]));
}
// If the key doesn't exist but a default was passed in, return it
if ($default) {
return $default;
}
// if the key doesn't exist, but running locally, throw an exception
if (App::isLocal()) {
throw new Exception("Element key '{$key}' is not declared in elements.yaml.");
}
// Otherwise, like if key doesn't exist and running on production,
// return an empty Element, whose ->toString() will return an empty string.
Log::error("Element key '{$key}' is not declared in elements.yaml.");
return new $this->model();
} | [
"public",
"function",
"get",
"(",
"$",
"key",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"hydrate",
"(",
")",
";",
"// Create an Element instance using the data for the key",
"if",
"(",
"$",
"this",
"->",
"has",
"(",
"$",
"key",
")",
... | Get an element given it's key
@param string $key
@return Bkwld\Decoy\Models\Element | [
"Get",
"an",
"element",
"given",
"it",
"s",
"key"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L88-L111 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.getMany | public function getMany($prefix, $crops = [])
{
// Get all of the elements matching the prefix with dot-notated keys
$dotted = $this
->hydrate()
->filter(function($val, $key) use ($prefix) {
return starts_with($key, $prefix);
// Loop through all matching elements
})->map(function($val, $key) use ($prefix, $crops) {
// Resolve the key using the Element helper so that we get an
// actual Element model instance.
$el = $this->get($key);
$value = $el->value();
// Check if the element key is in the $crops config. If so,
// return the croopped image instructions.
$crop_key = substr($key, strlen($prefix) + 1);
if (isset($crops[$crop_key])) {
// Handle models returned from BelongsTo fields
if (is_a($value, Base::class)) {
$func = [$value, 'withDefaultImage'];
return call_user_func_array($func, $crops[$crop_key]);
}
// Otherwise, use the crop helper on the Element model
return call_user_func_array([$el, 'crop'], $crops[$crop_key]);
}
// If no crops were defined, return the value
return (string) $value;
// Convert the collection to an array
})->all();
// Make a multidimensionsl array from the dots, stripping the prefix
// from the keys. Then return it.
$multi = [];
$len = strlen($prefix);
foreach($dotted as $key => $val) {
array_set($multi, trim(substr($key, $len), '.'), $val);
}
return $multi;
} | php | public function getMany($prefix, $crops = [])
{
// Get all of the elements matching the prefix with dot-notated keys
$dotted = $this
->hydrate()
->filter(function($val, $key) use ($prefix) {
return starts_with($key, $prefix);
// Loop through all matching elements
})->map(function($val, $key) use ($prefix, $crops) {
// Resolve the key using the Element helper so that we get an
// actual Element model instance.
$el = $this->get($key);
$value = $el->value();
// Check if the element key is in the $crops config. If so,
// return the croopped image instructions.
$crop_key = substr($key, strlen($prefix) + 1);
if (isset($crops[$crop_key])) {
// Handle models returned from BelongsTo fields
if (is_a($value, Base::class)) {
$func = [$value, 'withDefaultImage'];
return call_user_func_array($func, $crops[$crop_key]);
}
// Otherwise, use the crop helper on the Element model
return call_user_func_array([$el, 'crop'], $crops[$crop_key]);
}
// If no crops were defined, return the value
return (string) $value;
// Convert the collection to an array
})->all();
// Make a multidimensionsl array from the dots, stripping the prefix
// from the keys. Then return it.
$multi = [];
$len = strlen($prefix);
foreach($dotted as $key => $val) {
array_set($multi, trim(substr($key, $len), '.'), $val);
}
return $multi;
} | [
"public",
"function",
"getMany",
"(",
"$",
"prefix",
",",
"$",
"crops",
"=",
"[",
"]",
")",
"{",
"// Get all of the elements matching the prefix with dot-notated keys",
"$",
"dotted",
"=",
"$",
"this",
"->",
"hydrate",
"(",
")",
"->",
"filter",
"(",
"function",
... | Get a number of elements at once by passing in a first or second level
depth key. Like just `'homepage.marquee'`
@param string $prefix Any leading part of a key
@param array $crops Assoc array with Element partial keys for ITS keys
and values as an arary of crop()-style arguments
@return array | [
"Get",
"a",
"number",
"of",
"elements",
"at",
"once",
"by",
"passing",
"in",
"a",
"first",
"or",
"second",
"level",
"depth",
"key",
".",
"Like",
"just",
"homepage",
".",
"marquee"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L122-L167 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.mergeSources | protected function mergeSources()
{
$assoc = $this->assocConfig();
return array_replace_recursive($assoc,
// Get only the databse records whose keys are present in the YAML. This removes
// entries that may be from older YAML configs.
array_intersect_key($this->assocAdminChoices(), $assoc)
);
} | php | protected function mergeSources()
{
$assoc = $this->assocConfig();
return array_replace_recursive($assoc,
// Get only the databse records whose keys are present in the YAML. This removes
// entries that may be from older YAML configs.
array_intersect_key($this->assocAdminChoices(), $assoc)
);
} | [
"protected",
"function",
"mergeSources",
"(",
")",
"{",
"$",
"assoc",
"=",
"$",
"this",
"->",
"assocConfig",
"(",
")",
";",
"return",
"array_replace_recursive",
"(",
"$",
"assoc",
",",
"// Get only the databse records whose keys are present in the YAML. This removes",
... | Merge database records and config file into a single, flat associative array.
@return void | [
"Merge",
"database",
"records",
"and",
"config",
"file",
"into",
"a",
"single",
"flat",
"associative",
"array",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L280-L290 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.assocConfig | public function assocConfig($include_extra = false)
{
// Load the config data if it isn't already
if (!$this->config) {
$this->loadConfig();
}
// Loop through the YAML config and make flattened keys. The ternary
// operators in here allow a shorthand version of the YAML config as
// described in the docs.
$config = [];
foreach ($this->config as $page => $page_data) {
foreach (isset($page_data['sections']) ? $page_data['sections'] : $page_data as $section => $section_data) {
foreach (isset($section_data['fields']) ? $section_data['fields'] : $section_data as $field => $field_data) {
// Determine the type of field
$field_parts = explode(',', $field);
$field = $field_parts[0];
if (count($field_parts) == 2) {
$type = $field_parts[1];
} // If concatted onto the field name
elseif (is_array($field_data) && isset($field_data['type'])) {
$type = $field_data['type'];
} // Explicitly set
else {
$type = 'text';
} // Default type
// Determine the value
if (is_array($field_data) && array_key_exists('value', $field_data)) {
$value = $field_data['value'];
} elseif (is_scalar($field_data)) {
$value = $field_data;
} // String, boolean, int, etc
else {
$value = null;
}
// Build the value array
$el = ['type' => $type, 'value' => $value];
if ($this->has_extra || $include_extra) {
$this->mergeExtra($el, $field, $field_data);
$this->mergeExtra($el, $section, $section_data, 'section_');
$this->mergeExtra($el, $page, $page_data, 'page_');
$el['rules'] = isset($field_data['rules']) ? $field_data['rules'] : null;
}
// Add the config
$config["{$page}.{$section}.{$field}"] = $el;
}
}
}
// Return the flattened config
return $config;
} | php | public function assocConfig($include_extra = false)
{
// Load the config data if it isn't already
if (!$this->config) {
$this->loadConfig();
}
// Loop through the YAML config and make flattened keys. The ternary
// operators in here allow a shorthand version of the YAML config as
// described in the docs.
$config = [];
foreach ($this->config as $page => $page_data) {
foreach (isset($page_data['sections']) ? $page_data['sections'] : $page_data as $section => $section_data) {
foreach (isset($section_data['fields']) ? $section_data['fields'] : $section_data as $field => $field_data) {
// Determine the type of field
$field_parts = explode(',', $field);
$field = $field_parts[0];
if (count($field_parts) == 2) {
$type = $field_parts[1];
} // If concatted onto the field name
elseif (is_array($field_data) && isset($field_data['type'])) {
$type = $field_data['type'];
} // Explicitly set
else {
$type = 'text';
} // Default type
// Determine the value
if (is_array($field_data) && array_key_exists('value', $field_data)) {
$value = $field_data['value'];
} elseif (is_scalar($field_data)) {
$value = $field_data;
} // String, boolean, int, etc
else {
$value = null;
}
// Build the value array
$el = ['type' => $type, 'value' => $value];
if ($this->has_extra || $include_extra) {
$this->mergeExtra($el, $field, $field_data);
$this->mergeExtra($el, $section, $section_data, 'section_');
$this->mergeExtra($el, $page, $page_data, 'page_');
$el['rules'] = isset($field_data['rules']) ? $field_data['rules'] : null;
}
// Add the config
$config["{$page}.{$section}.{$field}"] = $el;
}
}
}
// Return the flattened config
return $config;
} | [
"public",
"function",
"assocConfig",
"(",
"$",
"include_extra",
"=",
"false",
")",
"{",
"// Load the config data if it isn't already",
"if",
"(",
"!",
"$",
"this",
"->",
"config",
")",
"{",
"$",
"this",
"->",
"loadConfig",
"(",
")",
";",
"}",
"// Loop through ... | Massage the YAML config file into a single, flat associative array
@param boolean $include_extra Include attibutes that are only needed by Admin UIs
@return array | [
"Massage",
"the",
"YAML",
"config",
"file",
"into",
"a",
"single",
"flat",
"associative",
"array"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L298-L353 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.mergeExtra | protected function mergeExtra(&$el, $key, $data, $prefix = null)
{
// Don't add extra if this in the 1st or 2nd depth (which means there is a prefix)
// and there is no node for the children. This prevents a FIELD named "label" to be
// treated as the the label for it's section.
$skip = $prefix && empty($data['sections']) && empty($data['fields']);
// Fields
if (isset($data['label']) && $data['label'] === false) {
$el[$prefix.'label'] = false;
} else {
$el[$prefix.'label'] = empty($data['label']) || $skip ? Utils\Text::titleFromKey($key) : $data['label'];
}
$el[$prefix.'help'] = empty($data['help']) || $skip ? null : $data['help'];
// Used by radio, select, and checkboxes types
$el[$prefix.'options'] = empty($data['options']) || $skip ? null : $data['options'];
// Used by belongs to but maybe others in the future
$el[$prefix.'class'] = empty($data['class']) || $skip ? null : $data['class'];
// Used by videoEncoder
$el[$prefix.'preset'] = empty($data['preset']) || $skip ? null : $data['preset'];
} | php | protected function mergeExtra(&$el, $key, $data, $prefix = null)
{
// Don't add extra if this in the 1st or 2nd depth (which means there is a prefix)
// and there is no node for the children. This prevents a FIELD named "label" to be
// treated as the the label for it's section.
$skip = $prefix && empty($data['sections']) && empty($data['fields']);
// Fields
if (isset($data['label']) && $data['label'] === false) {
$el[$prefix.'label'] = false;
} else {
$el[$prefix.'label'] = empty($data['label']) || $skip ? Utils\Text::titleFromKey($key) : $data['label'];
}
$el[$prefix.'help'] = empty($data['help']) || $skip ? null : $data['help'];
// Used by radio, select, and checkboxes types
$el[$prefix.'options'] = empty($data['options']) || $skip ? null : $data['options'];
// Used by belongs to but maybe others in the future
$el[$prefix.'class'] = empty($data['class']) || $skip ? null : $data['class'];
// Used by videoEncoder
$el[$prefix.'preset'] = empty($data['preset']) || $skip ? null : $data['preset'];
} | [
"protected",
"function",
"mergeExtra",
"(",
"&",
"$",
"el",
",",
"$",
"key",
",",
"$",
"data",
",",
"$",
"prefix",
"=",
"null",
")",
"{",
"// Don't add extra if this in the 1st or 2nd depth (which means there is a prefix)",
"// and there is no node for the children. This p... | Add label and help to the element data for one of the levels
@param array $el The element data that is being merged into, passed by reference
@param mixed $data The data for a level in the Elements YAML config
@param string $prefix A prefix to append to the beginning of the key being set on $el | [
"Add",
"label",
"and",
"help",
"to",
"the",
"element",
"data",
"for",
"one",
"of",
"the",
"levels"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L362-L385 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.assocAdminChoices | protected function assocAdminChoices()
{
// Build the query
$query = call_user_func([$this->model, 'query']);
if ($this->locale) {
$query->localize($this->locale);
}
// Convert models to simple array
$elements = array_map(function (Element $element) {
// Don't need the key as an attribute because of the dictionary conversion
$ar = array_except($element->toArray(), ['key']);
// Restore relationships
$ar['images'] = $element->images;
return $ar;
// .. from a dictionary of ALL elements for the locale
}, $query->get()->getDictionary());
// Store the keys of all these elements so we can keep track of which
// Elements "exist"
$this->updated_items = array_keys($elements);
// Return the elements
return $elements;
} | php | protected function assocAdminChoices()
{
// Build the query
$query = call_user_func([$this->model, 'query']);
if ($this->locale) {
$query->localize($this->locale);
}
// Convert models to simple array
$elements = array_map(function (Element $element) {
// Don't need the key as an attribute because of the dictionary conversion
$ar = array_except($element->toArray(), ['key']);
// Restore relationships
$ar['images'] = $element->images;
return $ar;
// .. from a dictionary of ALL elements for the locale
}, $query->get()->getDictionary());
// Store the keys of all these elements so we can keep track of which
// Elements "exist"
$this->updated_items = array_keys($elements);
// Return the elements
return $elements;
} | [
"protected",
"function",
"assocAdminChoices",
"(",
")",
"{",
"// Build the query",
"$",
"query",
"=",
"call_user_func",
"(",
"[",
"$",
"this",
"->",
"model",
",",
"'query'",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"locale",
")",
"{",
"$",
"query",
... | Get admin overrides to Elements from the databse
@return array | [
"Get",
"admin",
"overrides",
"to",
"Elements",
"from",
"the",
"databse"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L392-L420 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.loadConfig | protected function loadConfig()
{
// Start with empty config
$this->config = [];
// Build a lit of all the paths
$dir = config_path('decoy').'/';
$files = [];
if (is_readable($dir.'elements.yaml')) {
$files[] = $dir.'elements.yaml';
}
if (is_dir($dir.'elements')) {
$files = array_merge($files, glob($dir.'elements/*.yaml'));
}
if (!count($files)) {
return;
}
// Loop though config files and merge them together
foreach ($files as $file) {
// If an array found ...
if (($config = Yaml::parse(file_get_contents($file)))
&& is_array($config)) {
// Merge it in
$this->config = array_replace_recursive($this->config, $config);
}
}
} | php | protected function loadConfig()
{
// Start with empty config
$this->config = [];
// Build a lit of all the paths
$dir = config_path('decoy').'/';
$files = [];
if (is_readable($dir.'elements.yaml')) {
$files[] = $dir.'elements.yaml';
}
if (is_dir($dir.'elements')) {
$files = array_merge($files, glob($dir.'elements/*.yaml'));
}
if (!count($files)) {
return;
}
// Loop though config files and merge them together
foreach ($files as $file) {
// If an array found ...
if (($config = Yaml::parse(file_get_contents($file)))
&& is_array($config)) {
// Merge it in
$this->config = array_replace_recursive($this->config, $config);
}
}
} | [
"protected",
"function",
"loadConfig",
"(",
")",
"{",
"// Start with empty config",
"$",
"this",
"->",
"config",
"=",
"[",
"]",
";",
"// Build a lit of all the paths",
"$",
"dir",
"=",
"config_path",
"(",
"'decoy'",
")",
".",
"'/'",
";",
"$",
"files",
"=",
"... | Load the config file and store it internally
@return void | [
"Load",
"the",
"config",
"file",
"and",
"store",
"it",
"internally"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L441-L470 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.keyUpdated | public function keyUpdated($key)
{
if ($this->updated_items === null) {
$this->assocAdminChoices();
}
return in_array($key, $this->updated_items);
} | php | public function keyUpdated($key)
{
if ($this->updated_items === null) {
$this->assocAdminChoices();
}
return in_array($key, $this->updated_items);
} | [
"public",
"function",
"keyUpdated",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"updated_items",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"assocAdminChoices",
"(",
")",
";",
"}",
"return",
"in_array",
"(",
"$",
"key",
",",
"$",
"this"... | Check if a key has been stored in the database
@param string $key The key of an element
@return boolean | [
"Check",
"if",
"a",
"key",
"has",
"been",
"stored",
"in",
"the",
"database"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L478-L485 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.onlyPages | public function onlyPages($pages)
{
$this->items = array_filter($this->items, function ($element) use ($pages) {
return in_array(Str::slug($element['page_label']), $pages);
});
return $this;
} | php | public function onlyPages($pages)
{
$this->items = array_filter($this->items, function ($element) use ($pages) {
return in_array(Str::slug($element['page_label']), $pages);
});
return $this;
} | [
"public",
"function",
"onlyPages",
"(",
"$",
"pages",
")",
"{",
"$",
"this",
"->",
"items",
"=",
"array_filter",
"(",
"$",
"this",
"->",
"items",
",",
"function",
"(",
"$",
"element",
")",
"use",
"(",
"$",
"pages",
")",
"{",
"return",
"in_array",
"("... | Filter the elements to only those allowed in the provided pages
@param array $pages
@return $this | [
"Filter",
"the",
"elements",
"to",
"only",
"those",
"allowed",
"in",
"the",
"provided",
"pages"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L493-L500 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.rules | public function rules()
{
$rules = [];
foreach ($this->assocConfig(true) as $key => $data) {
if (empty($data['rules'])) {
continue;
}
$rules[str_replace('.', '|', $key)] = $data['rules'];
}
return $rules;
} | php | public function rules()
{
$rules = [];
foreach ($this->assocConfig(true) as $key => $data) {
if (empty($data['rules'])) {
continue;
}
$rules[str_replace('.', '|', $key)] = $data['rules'];
}
return $rules;
} | [
"public",
"function",
"rules",
"(",
")",
"{",
"$",
"rules",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"assocConfig",
"(",
"true",
")",
"as",
"$",
"key",
"=>",
"$",
"data",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"data",
"[",
"'rule... | Return the validation rules for the items. Convert the keys to the
expected input style
@return array An array of validation rules, keyed to element keys | [
"Return",
"the",
"validation",
"rules",
"for",
"the",
"items",
".",
"Convert",
"the",
"keys",
"to",
"the",
"expected",
"input",
"style"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L508-L519 | train |
BKWLD/decoy | classes/Collections/Elements.php | Elements.populate | public function populate()
{
return array_combine(array_map(function ($key) {
return str_replace('.', '|', $key);
}, $this->keys()->all()), $this->pluck('value')->all());
} | php | public function populate()
{
return array_combine(array_map(function ($key) {
return str_replace('.', '|', $key);
}, $this->keys()->all()), $this->pluck('value')->all());
} | [
"public",
"function",
"populate",
"(",
")",
"{",
"return",
"array_combine",
"(",
"array_map",
"(",
"function",
"(",
"$",
"key",
")",
"{",
"return",
"str_replace",
"(",
"'.'",
",",
"'|'",
",",
"$",
"key",
")",
";",
"}",
",",
"$",
"this",
"->",
"keys",... | Return key-value pairs for use by former to populate the fields. The
keys must be converted to the Input safe variant.
@return array | [
"Return",
"key",
"-",
"value",
"pairs",
"for",
"use",
"by",
"former",
"to",
"populate",
"the",
"fields",
".",
"The",
"keys",
"must",
"be",
"converted",
"to",
"the",
"Input",
"safe",
"variant",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Collections/Elements.php#L527-L532 | train |
BKWLD/decoy | classes/Fields/Upload.php | Upload.render | public function render()
{
// A file has already been uploaded
if ($this->value) {
// If it's required, show the icon but don't enforce it. There is already
// a file uploaded after all
if ($this->isRequired()) {
$this->setAttribute('required', null);
}
}
// Continue execution
return parent::render();
} | php | public function render()
{
// A file has already been uploaded
if ($this->value) {
// If it's required, show the icon but don't enforce it. There is already
// a file uploaded after all
if ($this->isRequired()) {
$this->setAttribute('required', null);
}
}
// Continue execution
return parent::render();
} | [
"public",
"function",
"render",
"(",
")",
"{",
"// A file has already been uploaded",
"if",
"(",
"$",
"this",
"->",
"value",
")",
"{",
"// If it's required, show the icon but don't enforce it. There is already",
"// a file uploaded after all",
"if",
"(",
"$",
"this",
"->",... | Prints out the current file upload field.
@return string An input tag | [
"Prints",
"out",
"the",
"current",
"file",
"upload",
"field",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Fields/Upload.php#L57-L71 | train |
BKWLD/decoy | classes/Observers/ManyToManyChecklist.php | ManyToManyChecklist.handle | public function handle($event, $payload)
{
list($model) = $payload;
// Check for matching input elements
foreach (Request::input() as $key => $val) {
if (preg_match('#^'.self::PREFIX.'(.+)#', $key, $matches)) {
$this->updateRelationship($model, $matches[1]);
}
}
} | php | public function handle($event, $payload)
{
list($model) = $payload;
// Check for matching input elements
foreach (Request::input() as $key => $val) {
if (preg_match('#^'.self::PREFIX.'(.+)#', $key, $matches)) {
$this->updateRelationship($model, $matches[1]);
}
}
} | [
"public",
"function",
"handle",
"(",
"$",
"event",
",",
"$",
"payload",
")",
"{",
"list",
"(",
"$",
"model",
")",
"=",
"$",
"payload",
";",
"// Check for matching input elements",
"foreach",
"(",
"Request",
"::",
"input",
"(",
")",
"as",
"$",
"key",
"=>"... | Take input from a Many to Many Checklist and commit it to the db. Called
on model saved.
@param string $event
@param array $payload Contains:
- Bkwld\Decoy\Models\Base $model
@return void | [
"Take",
"input",
"from",
"a",
"Many",
"to",
"Many",
"Checklist",
"and",
"commit",
"it",
"to",
"the",
"db",
".",
"Called",
"on",
"model",
"saved",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Observers/ManyToManyChecklist.php#L28-L38 | train |
BKWLD/decoy | classes/Observers/ManyToManyChecklist.php | ManyToManyChecklist.updateRelationship | private function updateRelationship($model, $relationship)
{
// Make sure the relationship exists on the model. This also prevents the
// wrong model (who might also have an `saved` callback) from trying to have
// this data saved on it
if (!method_exists($model, $relationship)) {
return;
}
// Strip all the "0"s from the input. These exist because push checkboxes
// is globally set for all of Decoy;
$ids = request(self::PREFIX.$relationship);
$ids = array_filter($ids, function ($id) {
return $id > 0;
});
// Allow a single listener to transform the list of ids to, for instance,
// add pivot data.
$prefix = 'decoy::many-to-many-checklist.';
if ($mutated = Event::until($prefix."syncing: $relationship", [$ids])) {
$ids = $mutated;
}
// Attach just the ones mentioned in the input. This blows away the
// previous joins
$model->$relationship()->sync($ids);
// Fire completion event
Event::fire($prefix."synced: $relationship");
} | php | private function updateRelationship($model, $relationship)
{
// Make sure the relationship exists on the model. This also prevents the
// wrong model (who might also have an `saved` callback) from trying to have
// this data saved on it
if (!method_exists($model, $relationship)) {
return;
}
// Strip all the "0"s from the input. These exist because push checkboxes
// is globally set for all of Decoy;
$ids = request(self::PREFIX.$relationship);
$ids = array_filter($ids, function ($id) {
return $id > 0;
});
// Allow a single listener to transform the list of ids to, for instance,
// add pivot data.
$prefix = 'decoy::many-to-many-checklist.';
if ($mutated = Event::until($prefix."syncing: $relationship", [$ids])) {
$ids = $mutated;
}
// Attach just the ones mentioned in the input. This blows away the
// previous joins
$model->$relationship()->sync($ids);
// Fire completion event
Event::fire($prefix."synced: $relationship");
} | [
"private",
"function",
"updateRelationship",
"(",
"$",
"model",
",",
"$",
"relationship",
")",
"{",
"// Make sure the relationship exists on the model. This also prevents the",
"// wrong model (who might also have an `saved` callback) from trying to have",
"// this data saved on it",
"i... | Process a particular input instance
@param Bkwld\Decoy\Models\Base $model A model instance
@param string $relationship The relationship name | [
"Process",
"a",
"particular",
"input",
"instance"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Observers/ManyToManyChecklist.php#L46-L75 | train |
BKWLD/decoy | classes/Input/ModelValidator.php | ModelValidator.validate | public function validate(BaseModel $model, $rules = null, $messages = [])
{
return $this->validateAndPrefixErrors(null, $model, $rules, $messages);
} | php | public function validate(BaseModel $model, $rules = null, $messages = [])
{
return $this->validateAndPrefixErrors(null, $model, $rules, $messages);
} | [
"public",
"function",
"validate",
"(",
"BaseModel",
"$",
"model",
",",
"$",
"rules",
"=",
"null",
",",
"$",
"messages",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"validateAndPrefixErrors",
"(",
"null",
",",
"$",
"model",
",",
"$",
"rules",
... | Validate a model, firing Decoy events
@param BaseModel $data
@param array $rules A Laravel rules array. If null, will be pulled from model
@param array $messages Special error messages
@return Validator | [
"Validate",
"a",
"model",
"firing",
"Decoy",
"events"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/ModelValidator.php#L25-L28 | train |
BKWLD/decoy | classes/Input/ModelValidator.php | ModelValidator.handleImageRules | public function handleImageRules($model, $rules)
{
// If the model is an image, the rules were passed in by NestedModels
// and are good to go
if (is_a($model, Image::class)) {
return $rules;
}
// Otherwise, remove any image rules because this is a non-Image and
// these rules will get applied by NestedModels
return array_where($rules, function ($val, $key) {
return !starts_with($key, 'images.');
});
} | php | public function handleImageRules($model, $rules)
{
// If the model is an image, the rules were passed in by NestedModels
// and are good to go
if (is_a($model, Image::class)) {
return $rules;
}
// Otherwise, remove any image rules because this is a non-Image and
// these rules will get applied by NestedModels
return array_where($rules, function ($val, $key) {
return !starts_with($key, 'images.');
});
} | [
"public",
"function",
"handleImageRules",
"(",
"$",
"model",
",",
"$",
"rules",
")",
"{",
"// If the model is an image, the rules were passed in by NestedModels",
"// and are good to go",
"if",
"(",
"is_a",
"(",
"$",
"model",
",",
"Image",
"::",
"class",
")",
")",
"... | Handle the Images feature, which is special because you define the rules
on the parent model.
@param BaseModel $data
@param array $rules A Laravel rules array. If null, will be pulled from model
@return array | [
"Handle",
"the",
"Images",
"feature",
"which",
"is",
"special",
"because",
"you",
"define",
"the",
"rules",
"on",
"the",
"parent",
"model",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/ModelValidator.php#L96-L110 | train |
BKWLD/decoy | classes/Input/ModelValidator.php | ModelValidator.nestArray | public function nestArray($prefix, $array)
{
$data = [];
foreach($array as $key => $value) {
array_set($data, $prefix.$key, $value);
}
return $data;
} | php | public function nestArray($prefix, $array)
{
$data = [];
foreach($array as $key => $value) {
array_set($data, $prefix.$key, $value);
}
return $data;
} | [
"public",
"function",
"nestArray",
"(",
"$",
"prefix",
",",
"$",
"array",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"array_set",
"(",
"$",
"data",
",",
"$",
"prefix",
... | Nest an array at another depth using the prefix
@param string $prefix
@param array $array
@return array | [
"Nest",
"an",
"array",
"at",
"another",
"depth",
"using",
"the",
"prefix"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/ModelValidator.php#L119-L126 | train |
BKWLD/decoy | classes/Input/ModelValidator.php | ModelValidator.prefixArrayKeys | public function prefixArrayKeys($prefix, $array)
{
return array_combine(array_map(function ($key) use ($prefix) {
return $prefix.$key;
}, array_keys($array)), array_values($array));
} | php | public function prefixArrayKeys($prefix, $array)
{
return array_combine(array_map(function ($key) use ($prefix) {
return $prefix.$key;
}, array_keys($array)), array_values($array));
} | [
"public",
"function",
"prefixArrayKeys",
"(",
"$",
"prefix",
",",
"$",
"array",
")",
"{",
"return",
"array_combine",
"(",
"array_map",
"(",
"function",
"(",
"$",
"key",
")",
"use",
"(",
"$",
"prefix",
")",
"{",
"return",
"$",
"prefix",
".",
"$",
"key",... | Apply a prefix to the keys of an array
@param string $prefix
@param array $array
@return array | [
"Apply",
"a",
"prefix",
"to",
"the",
"keys",
"of",
"an",
"array"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/ModelValidator.php#L135-L140 | train |
BKWLD/decoy | classes/Input/ModelValidator.php | ModelValidator.removePrefixFromMessages | protected function removePrefixFromMessages($prefix, $validator)
{
// Get all the rules in a single flat array
$rules = array_flatten($validator->getRules());
// Get just the rules, not rule modifiers
$rules = array_map(function($rule) {
preg_match('#^([^:]+)#', $rule, $matches);
return $matches[1];
}, $rules);
// Callback that removes isntances of the prefix from a message. Laravel
// will have already replaced underscores with spaces, so we need to
// reverse that.
$prefix = str_replace('_', ' ', $prefix);
$replacer = function ($message) use ($prefix) {
return str_replace($prefix, '', $message);
};
// Create an array of identical replacer functions
$replacers = array_fill(0, count($rules), $replacer);
// Add the replacers to the validtor
$validator->addReplacers(array_combine($rules, $replacers));
} | php | protected function removePrefixFromMessages($prefix, $validator)
{
// Get all the rules in a single flat array
$rules = array_flatten($validator->getRules());
// Get just the rules, not rule modifiers
$rules = array_map(function($rule) {
preg_match('#^([^:]+)#', $rule, $matches);
return $matches[1];
}, $rules);
// Callback that removes isntances of the prefix from a message. Laravel
// will have already replaced underscores with spaces, so we need to
// reverse that.
$prefix = str_replace('_', ' ', $prefix);
$replacer = function ($message) use ($prefix) {
return str_replace($prefix, '', $message);
};
// Create an array of identical replacer functions
$replacers = array_fill(0, count($rules), $replacer);
// Add the replacers to the validtor
$validator->addReplacers(array_combine($rules, $replacers));
} | [
"protected",
"function",
"removePrefixFromMessages",
"(",
"$",
"prefix",
",",
"$",
"validator",
")",
"{",
"// Get all the rules in a single flat array",
"$",
"rules",
"=",
"array_flatten",
"(",
"$",
"validator",
"->",
"getRules",
"(",
")",
")",
";",
"// Get just the... | Add replacers to the validator that strip back out the prefix
@param string $prefix
@param Illuminate\Validation\Validator $validator
@return void | [
"Add",
"replacers",
"to",
"the",
"validator",
"that",
"strip",
"back",
"out",
"the",
"prefix"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/ModelValidator.php#L149-L173 | train |
BKWLD/decoy | classes/Input/Search.php | Search.query | public static function query($terms)
{
return 'query='.urlencode(json_encode(array_map(function ($input, $field) {
return [$field, '=', $input];
}, $terms, array_keys($terms))));
} | php | public static function query($terms)
{
return 'query='.urlencode(json_encode(array_map(function ($input, $field) {
return [$field, '=', $input];
}, $terms, array_keys($terms))));
} | [
"public",
"static",
"function",
"query",
"(",
"$",
"terms",
")",
"{",
"return",
"'query='",
".",
"urlencode",
"(",
"json_encode",
"(",
"array_map",
"(",
"function",
"(",
"$",
"input",
",",
"$",
"field",
")",
"{",
"return",
"[",
"$",
"field",
",",
"'='"... | Utility method to generate a query string that applies the condition
provided in the args
@param array $terms An associative array where the keys are "fields"
and the values are "inputs"
@return string | [
"Utility",
"method",
"to",
"generate",
"a",
"query",
"string",
"that",
"applies",
"the",
"condition",
"provided",
"in",
"the",
"args"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/Search.php#L27-L32 | train |
BKWLD/decoy | classes/Input/Search.php | Search.condition | private function condition($query, $field, $comparison, $input, $type)
{
// Convert date formats
if ($type == 'date') {
$field = $this->convertDateField($field);
$input = Carbon::createFromFormat(__('decoy::form.date.format'), $input)
->format('Y-m-d');
}
// Apply the where
switch ($comparison) {
// NULL safe equals and not equals
case '=':
case '!=':
return $this->applyEquality($comparison, $query, $field, $input);
// Not Like
case '!%*%':
$comparison = substr($comparison, 1);
$input = str_replace('*', $input, $comparison);
return $query->where($field, 'NOT LIKE', $input);
// Like
case '*%':
case '%*':
case '%*%':
$input = str_replace('*', $input, $comparison);
return $query->where($field, 'LIKE', $input);
// Defaults
default:
return $query->where($field, $comparison, $input);
}
} | php | private function condition($query, $field, $comparison, $input, $type)
{
// Convert date formats
if ($type == 'date') {
$field = $this->convertDateField($field);
$input = Carbon::createFromFormat(__('decoy::form.date.format'), $input)
->format('Y-m-d');
}
// Apply the where
switch ($comparison) {
// NULL safe equals and not equals
case '=':
case '!=':
return $this->applyEquality($comparison, $query, $field, $input);
// Not Like
case '!%*%':
$comparison = substr($comparison, 1);
$input = str_replace('*', $input, $comparison);
return $query->where($field, 'NOT LIKE', $input);
// Like
case '*%':
case '%*':
case '%*%':
$input = str_replace('*', $input, $comparison);
return $query->where($field, 'LIKE', $input);
// Defaults
default:
return $query->where($field, $comparison, $input);
}
} | [
"private",
"function",
"condition",
"(",
"$",
"query",
",",
"$",
"field",
",",
"$",
"comparison",
",",
"$",
"input",
",",
"$",
"type",
")",
"{",
"// Convert date formats",
"if",
"(",
"$",
"type",
"==",
"'date'",
")",
"{",
"$",
"field",
"=",
"$",
"thi... | Add a condition to a query
@param Illuminate\Database\Query\Builder $query
@param string $field The field name from search config
@param string $comparison The operator string from the search UI
@param string $input The input for the field
@param string $type The type of the field
@return Illuminate\Database\Query\Builder | [
"Add",
"a",
"condition",
"to",
"a",
"query"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/Search.php#L93-L127 | train |
BKWLD/decoy | classes/Input/Search.php | Search.applyEquality | protected function applyEquality($comparison, $query, $field, $input)
{
// Make SQL safe values
$safe_field = $this->makeSafeField($field);
$safe_input = $input == '' ?
'NULL' : DB::connection()->getPdo()->quote($input);
// Different engines have different APIs
switch(DB::getDriverName())
{
case 'mysql': return $this->applyMysqlEquality(
$comparison, $query, $safe_field, $safe_input);
case 'sqlite': return $this->applySqliteEquality(
$comparison, $query, $safe_field, $safe_input);
case 'sqlsrv': return $this->applySqlServerEquality(
$comparison, $query, $safe_field, $safe_input);
}
} | php | protected function applyEquality($comparison, $query, $field, $input)
{
// Make SQL safe values
$safe_field = $this->makeSafeField($field);
$safe_input = $input == '' ?
'NULL' : DB::connection()->getPdo()->quote($input);
// Different engines have different APIs
switch(DB::getDriverName())
{
case 'mysql': return $this->applyMysqlEquality(
$comparison, $query, $safe_field, $safe_input);
case 'sqlite': return $this->applySqliteEquality(
$comparison, $query, $safe_field, $safe_input);
case 'sqlsrv': return $this->applySqlServerEquality(
$comparison, $query, $safe_field, $safe_input);
}
} | [
"protected",
"function",
"applyEquality",
"(",
"$",
"comparison",
",",
"$",
"query",
",",
"$",
"field",
",",
"$",
"input",
")",
"{",
"// Make SQL safe values",
"$",
"safe_field",
"=",
"$",
"this",
"->",
"makeSafeField",
"(",
"$",
"field",
")",
";",
"$",
... | Make the NULL-safe equals query
@param string $comparison
@param Builder $query
@param string $field
@param string $input
@return Builder | [
"Make",
"the",
"NULL",
"-",
"safe",
"equals",
"query"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/Search.php#L154-L171 | train |
BKWLD/decoy | classes/Input/Search.php | Search.longhand | public function longhand($config)
{
$search = [];
foreach ($config as $key => $val) {
// Make locale menu
if ($val == 'locale') {
$search['locale'] = [
'type' => 'select',
'label' => 'Locale',
'options' => Config::get('decoy.site.locales'),
];
// Not associative assume it's a text field
} elseif (is_numeric($key)) {
$search[$val] = ['type' => 'text', 'label' => Text::titleFromKey($val)];
// If value isn't an array, make a default label
} elseif (!is_array($val)) {
$search[$key] = ['type' => $val, 'label' => Text::titleFromKey($key)];
// Add the meta array
} else {
// Make a default label
if (empty($val['label'])) {
$val['label'] = Text::titleFromKey($key);
}
// Support class static method or variable as options for a select
if (!empty($val['type'])
&& $val['type'] == 'select'
&& !empty($val['options'])
&& is_string($val['options'])) {
$val['options'] = $this->longhandOptions($val['options']);
}
// Apply the meta data
$search[$key] = $val;
}
}
return $search;
} | php | public function longhand($config)
{
$search = [];
foreach ($config as $key => $val) {
// Make locale menu
if ($val == 'locale') {
$search['locale'] = [
'type' => 'select',
'label' => 'Locale',
'options' => Config::get('decoy.site.locales'),
];
// Not associative assume it's a text field
} elseif (is_numeric($key)) {
$search[$val] = ['type' => 'text', 'label' => Text::titleFromKey($val)];
// If value isn't an array, make a default label
} elseif (!is_array($val)) {
$search[$key] = ['type' => $val, 'label' => Text::titleFromKey($key)];
// Add the meta array
} else {
// Make a default label
if (empty($val['label'])) {
$val['label'] = Text::titleFromKey($key);
}
// Support class static method or variable as options for a select
if (!empty($val['type'])
&& $val['type'] == 'select'
&& !empty($val['options'])
&& is_string($val['options'])) {
$val['options'] = $this->longhandOptions($val['options']);
}
// Apply the meta data
$search[$key] = $val;
}
}
return $search;
} | [
"public",
"function",
"longhand",
"(",
"$",
"config",
")",
"{",
"$",
"search",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"config",
"as",
"$",
"key",
"=>",
"$",
"val",
")",
"{",
"// Make locale menu",
"if",
"(",
"$",
"val",
"==",
"'locale'",
")",
"{"... | Make the shorthand options of the search config explicit
@param array $config Search config from the controller class definition
@return array | [
"Make",
"the",
"shorthand",
"options",
"of",
"the",
"search",
"config",
"explicit"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/Search.php#L261-L304 | train |
BKWLD/decoy | classes/Input/Search.php | Search.longhandOptions | private function longhandOptions($options)
{
// Call static method. You don't pass the paranethesis
// to static calls
if (preg_match('#::.+\(\)#', $options)) {
return call_user_func(substr($options, 0, strlen($options) - 2));
}
// Return static variable
if (preg_match('#::\$#', $options)) {
list($class, $var) = explode('::$', $options);
return $class::$$var;
}
// Unknown format
throw new Exception('Could not parse option: '.$options);
} | php | private function longhandOptions($options)
{
// Call static method. You don't pass the paranethesis
// to static calls
if (preg_match('#::.+\(\)#', $options)) {
return call_user_func(substr($options, 0, strlen($options) - 2));
}
// Return static variable
if (preg_match('#::\$#', $options)) {
list($class, $var) = explode('::$', $options);
return $class::$$var;
}
// Unknown format
throw new Exception('Could not parse option: '.$options);
} | [
"private",
"function",
"longhandOptions",
"(",
"$",
"options",
")",
"{",
"// Call static method. You don't pass the paranethesis",
"// to static calls",
"if",
"(",
"preg_match",
"(",
"'#::.+\\(\\)#'",
",",
"$",
"options",
")",
")",
"{",
"return",
"call_user_func",
"(",... | Parse select options, returning a transformed array with static arrays
or callbacks executed
@param array $options
@return array | [
"Parse",
"select",
"options",
"returning",
"a",
"transformed",
"array",
"with",
"static",
"arrays",
"or",
"callbacks",
"executed"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/Search.php#L313-L330 | train |
BKWLD/decoy | classes/Input/Search.php | Search.makeSoftDeletesCondition | public function makeSoftDeletesCondition($controller)
{
if (!$controller->withTrashed()) return [];
return [
'deleted_at' => [
'type' => 'select',
'label' => 'status',
'options' => [
'exists' => 'exists',
'deleted' => 'deleted'
],
'query' => function($query, $condition, $input) {
// If not deleted...
if (($input == 'exists' && $condition == '=') ||
($input == 'deleted' && $condition == '!=')) {
$query->whereNull('deleted_at');
// If deleted...
} else if (($input == 'deleted' && $condition == '=') ||
($input == 'exists' && $condition == '!=')) {
$query->whereNotNull('deleted_at');
}
},
]
];
} | php | public function makeSoftDeletesCondition($controller)
{
if (!$controller->withTrashed()) return [];
return [
'deleted_at' => [
'type' => 'select',
'label' => 'status',
'options' => [
'exists' => 'exists',
'deleted' => 'deleted'
],
'query' => function($query, $condition, $input) {
// If not deleted...
if (($input == 'exists' && $condition == '=') ||
($input == 'deleted' && $condition == '!=')) {
$query->whereNull('deleted_at');
// If deleted...
} else if (($input == 'deleted' && $condition == '=') ||
($input == 'exists' && $condition == '!=')) {
$query->whereNotNull('deleted_at');
}
},
]
];
} | [
"public",
"function",
"makeSoftDeletesCondition",
"(",
"$",
"controller",
")",
"{",
"if",
"(",
"!",
"$",
"controller",
"->",
"withTrashed",
"(",
")",
")",
"return",
"[",
"]",
";",
"return",
"[",
"'deleted_at'",
"=>",
"[",
"'type'",
"=>",
"'select'",
",",
... | Make soft deletes condition if the controller supports trashed records.
Returns an array so it can be easily merged into exisitng configs.
@param Controller\Base $controller
@return array | [
"Make",
"soft",
"deletes",
"condition",
"if",
"the",
"controller",
"supports",
"trashed",
"records",
".",
"Returns",
"an",
"array",
"so",
"it",
"can",
"be",
"easily",
"merged",
"into",
"exisitng",
"configs",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/Search.php#L339-L365 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.onCreating | public function onCreating()
{
// Delete any other encoding jobs for the same parent and field
self::where('encodable_type', '=', $this->encodable_type)
->where('encodable_id', '=', $this->encodable_id)
->where('encodable_attribute', '=', $this->encodable_attribute)
->delete();
// Default values
$this->status = 'pending';
} | php | public function onCreating()
{
// Delete any other encoding jobs for the same parent and field
self::where('encodable_type', '=', $this->encodable_type)
->where('encodable_id', '=', $this->encodable_id)
->where('encodable_attribute', '=', $this->encodable_attribute)
->delete();
// Default values
$this->status = 'pending';
} | [
"public",
"function",
"onCreating",
"(",
")",
"{",
"// Delete any other encoding jobs for the same parent and field",
"self",
"::",
"where",
"(",
"'encodable_type'",
",",
"'='",
",",
"$",
"this",
"->",
"encodable_type",
")",
"->",
"where",
"(",
"'encodable_id'",
",",
... | Set default fields and delete any old encodings for the same source.
@return void | [
"Set",
"default",
"fields",
"and",
"delete",
"any",
"old",
"encodings",
"for",
"the",
"same",
"source",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L69-L79 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.onDeleted | public function onDeleted()
{
// Get the directory of an output
if (($sources = (array) $this->outputs) // Convert sources to an array
&& count($sources) // If there are sources
&& ($first = array_pop($sources)) // Get the last source
&& preg_match('#^/(?!/)#', $first) // Make sure it's a local path
&& ($dir = public_path().dirname($first)) // Get the path of the filename
&& is_dir($dir)) { // Make sure it's a directory
File::deleteDir($dir);
}
} | php | public function onDeleted()
{
// Get the directory of an output
if (($sources = (array) $this->outputs) // Convert sources to an array
&& count($sources) // If there are sources
&& ($first = array_pop($sources)) // Get the last source
&& preg_match('#^/(?!/)#', $first) // Make sure it's a local path
&& ($dir = public_path().dirname($first)) // Get the path of the filename
&& is_dir($dir)) { // Make sure it's a directory
File::deleteDir($dir);
}
} | [
"public",
"function",
"onDeleted",
"(",
")",
"{",
"// Get the directory of an output",
"if",
"(",
"(",
"$",
"sources",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"outputs",
")",
"// Convert sources to an array",
"&&",
"count",
"(",
"$",
"sources",
")",
"// If ... | Delete encoded files that are local to this filesystem | [
"Delete",
"encoded",
"files",
"that",
"are",
"local",
"to",
"this",
"filesystem"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L97-L108 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.source | public function source()
{
$val = $this->encodable->{$this->encodable_attribute};
if (preg_match('#^http#', $val)) {
return $val;
}
return URL::asset($val);
} | php | public function source()
{
$val = $this->encodable->{$this->encodable_attribute};
if (preg_match('#^http#', $val)) {
return $val;
}
return URL::asset($val);
} | [
"public",
"function",
"source",
"(",
")",
"{",
"$",
"val",
"=",
"$",
"this",
"->",
"encodable",
"->",
"{",
"$",
"this",
"->",
"encodable_attribute",
"}",
";",
"if",
"(",
"preg_match",
"(",
"'#^http#'",
",",
"$",
"val",
")",
")",
"{",
"return",
"$",
... | Get the source video for the encode
@return string The path to the video relative to the document root | [
"Get",
"the",
"source",
"video",
"for",
"the",
"encode"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L150-L158 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.storeJob | public function storeJob($job_id, $outputs = null)
{
$this->status = 'queued';
$this->job_id = $job_id;
$this->outputs = $outputs;
$this->save();
} | php | public function storeJob($job_id, $outputs = null)
{
$this->status = 'queued';
$this->job_id = $job_id;
$this->outputs = $outputs;
$this->save();
} | [
"public",
"function",
"storeJob",
"(",
"$",
"job_id",
",",
"$",
"outputs",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"status",
"=",
"'queued'",
";",
"$",
"this",
"->",
"job_id",
"=",
"$",
"job_id",
";",
"$",
"this",
"->",
"outputs",
"=",
"$",
"outp... | Store a record of the encoding job
@param string $job_id A unique id generated by the service
@param mixed $outputs An optional assoc array where the keys are
labels for the outputs and the values are
absolute paths of where the output will be saved
@return void | [
"Store",
"a",
"record",
"of",
"the",
"encoding",
"job"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L169-L175 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.status | public function status($status, $message = null)
{
if (!in_array($status, static::$states)) {
throw new Exception('Unknown state: '.$status);
}
// If the current status is complete, don't update again. I have seen cases of a late
// processing call on a HLS stream file after it's already been set to complete. I think
// it could just be weird internet delays.
if ($this->complete == 'complete') {
return;
}
// Append messages
if ($this->message) {
$this->message .= ' ';
}
if ($message) {
$this->message .= $message;
}
// If a job is errored, don't unset it. Thus, if one output fails, a notification
// from a later output succeeding still means an overall failure.
if ($this->status != 'error') {
$this->status = $status;
}
// Save it
$this->save();
} | php | public function status($status, $message = null)
{
if (!in_array($status, static::$states)) {
throw new Exception('Unknown state: '.$status);
}
// If the current status is complete, don't update again. I have seen cases of a late
// processing call on a HLS stream file after it's already been set to complete. I think
// it could just be weird internet delays.
if ($this->complete == 'complete') {
return;
}
// Append messages
if ($this->message) {
$this->message .= ' ';
}
if ($message) {
$this->message .= $message;
}
// If a job is errored, don't unset it. Thus, if one output fails, a notification
// from a later output succeeding still means an overall failure.
if ($this->status != 'error') {
$this->status = $status;
}
// Save it
$this->save();
} | [
"public",
"function",
"status",
"(",
"$",
"status",
",",
"$",
"message",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"status",
",",
"static",
"::",
"$",
"states",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Unknown state: '",
... | Update the status of the encode
@param string status
@param string $message
@return void | [
"Update",
"the",
"status",
"of",
"the",
"encode"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L184-L214 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.getAdminVideoTagAttribute | public function getAdminVideoTagAttribute()
{
if (!$tag = $this->getTagAttribute()) {
return;
}
$tag->controls();
if (isset($this->response->output->width)) {
$tag->width($this->response->output->width);
}
return $tag->render();
} | php | public function getAdminVideoTagAttribute()
{
if (!$tag = $this->getTagAttribute()) {
return;
}
$tag->controls();
if (isset($this->response->output->width)) {
$tag->width($this->response->output->width);
}
return $tag->render();
} | [
"public",
"function",
"getAdminVideoTagAttribute",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"tag",
"=",
"$",
"this",
"->",
"getTagAttribute",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"tag",
"->",
"controls",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"... | Generate an HTML5 video tag with extra elements for displaying in the admin
@return string html | [
"Generate",
"an",
"HTML5",
"video",
"tag",
"with",
"extra",
"elements",
"for",
"displaying",
"in",
"the",
"admin"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L234-L246 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.getAdminStatsMarkupAttribute | protected function getAdminStatsMarkupAttribute()
{
if (!$stats = $this->getStatsAttribute()) {
return '';
}
return '<div class="stats">'
.implode('', array_map(function ($val, $key) {
return sprintf('<span class="label">
<span>%s</span>
<span class="badge">%s</span>
</span>',
$key, $val);
}, $stats, array_keys($stats)))
.'</div>';
} | php | protected function getAdminStatsMarkupAttribute()
{
if (!$stats = $this->getStatsAttribute()) {
return '';
}
return '<div class="stats">'
.implode('', array_map(function ($val, $key) {
return sprintf('<span class="label">
<span>%s</span>
<span class="badge">%s</span>
</span>',
$key, $val);
}, $stats, array_keys($stats)))
.'</div>';
} | [
"protected",
"function",
"getAdminStatsMarkupAttribute",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"stats",
"=",
"$",
"this",
"->",
"getStatsAttribute",
"(",
")",
")",
"{",
"return",
"''",
";",
"}",
"return",
"'<div class=\"stats\">'",
".",
"implode",
"(",
"''",
... | Get stats as labels with badges
@return string html | [
"Get",
"stats",
"as",
"labels",
"with",
"badges"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L253-L268 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.getStatsAttribute | protected function getStatsAttribute()
{
if (empty($this->response->output)) {
return;
}
$o = $this->response->output;
return array_filter([
'Bitrate' => number_format($o->video_bitrate_in_kbps
+ $o->audio_bitrate_in_kbps).' kbps',
'Filesize' => number_format($o->file_size_in_bytes/1024/1024, 1).' mb',
'Duration' => number_format($o->duration_in_ms/1000, 1).' s',
'Dimensions' => number_format($o->width).' x '.number_format($o->height),
'Download' => '<a href="'.$this->outputs->mp4.'" target="_blank">MP4</a>'
]);
} | php | protected function getStatsAttribute()
{
if (empty($this->response->output)) {
return;
}
$o = $this->response->output;
return array_filter([
'Bitrate' => number_format($o->video_bitrate_in_kbps
+ $o->audio_bitrate_in_kbps).' kbps',
'Filesize' => number_format($o->file_size_in_bytes/1024/1024, 1).' mb',
'Duration' => number_format($o->duration_in_ms/1000, 1).' s',
'Dimensions' => number_format($o->width).' x '.number_format($o->height),
'Download' => '<a href="'.$this->outputs->mp4.'" target="_blank">MP4</a>'
]);
} | [
"protected",
"function",
"getStatsAttribute",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"response",
"->",
"output",
")",
")",
"{",
"return",
";",
"}",
"$",
"o",
"=",
"$",
"this",
"->",
"response",
"->",
"output",
";",
"return",
"arra... | Read an array of stats from the response
@return array|void | [
"Read",
"an",
"array",
"of",
"stats",
"from",
"the",
"response"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L275-L290 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.getTagAttribute | public function getTagAttribute()
{
// Require sources and for the encoding to be complete
if (!$sources = $this->getOutputsValue()) {
return;
}
// Start the tag
$tag = HtmlElement::video();
$tag->value('Your browser does not support the video tag. You should <a href="http://whatbrowser.org/">consider updating</a>.');
// Loop through the outputs and add them as sources
$types = ['mp4', 'webm', 'ogg', 'playlist'];
foreach ($sources as $type => $src) {
// Only allow basic output types
if (!in_array($type, $types)) {
continue;
}
// Make the source
$source = HtmlElement::source()->src($src);
if ($type == 'playlist') {
$source->type('application/x-mpegurl');
} else {
$source->type('video/'.$type);
}
// Add a source to the video tag
$tag->appendChild($source);
}
// Return the tag
return $tag;
} | php | public function getTagAttribute()
{
// Require sources and for the encoding to be complete
if (!$sources = $this->getOutputsValue()) {
return;
}
// Start the tag
$tag = HtmlElement::video();
$tag->value('Your browser does not support the video tag. You should <a href="http://whatbrowser.org/">consider updating</a>.');
// Loop through the outputs and add them as sources
$types = ['mp4', 'webm', 'ogg', 'playlist'];
foreach ($sources as $type => $src) {
// Only allow basic output types
if (!in_array($type, $types)) {
continue;
}
// Make the source
$source = HtmlElement::source()->src($src);
if ($type == 'playlist') {
$source->type('application/x-mpegurl');
} else {
$source->type('video/'.$type);
}
// Add a source to the video tag
$tag->appendChild($source);
}
// Return the tag
return $tag;
} | [
"public",
"function",
"getTagAttribute",
"(",
")",
"{",
"// Require sources and for the encoding to be complete",
"if",
"(",
"!",
"$",
"sources",
"=",
"$",
"this",
"->",
"getOutputsValue",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Start the tag",
"$",
"tag",
"... | Generate an HTML5 video tag via Former's HtmlObject for the outputs
@return HtmlObject\Element | [
"Generate",
"an",
"HTML5",
"video",
"tag",
"via",
"Former",
"s",
"HtmlObject",
"for",
"the",
"outputs"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L316-L350 | train |
BKWLD/decoy | classes/Models/Encoding.php | Encoding.getOutputsValue | public function getOutputsValue()
{
if ($this->status != 'complete') {
return;
}
$val = $this->getAttributeFromArray('outputs');
if (is_string($val)) {
return $this->outputs;
}
return $val;
} | php | public function getOutputsValue()
{
if ($this->status != 'complete') {
return;
}
$val = $this->getAttributeFromArray('outputs');
if (is_string($val)) {
return $this->outputs;
}
return $val;
} | [
"public",
"function",
"getOutputsValue",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"status",
"!=",
"'complete'",
")",
"{",
"return",
";",
"}",
"$",
"val",
"=",
"$",
"this",
"->",
"getAttributeFromArray",
"(",
"'outputs'",
")",
";",
"if",
"(",
"is_st... | Get the outputs value. I made this to work around an issue where Laravel
was double casting the outputs. I'm not sure why this was happening after
some lengthy digging but it seemed unique to Encodings on Elements. So I'm
testing whether the attribute value has already been casted.
@return object | [
"Get",
"the",
"outputs",
"value",
".",
"I",
"made",
"this",
"to",
"work",
"around",
"an",
"issue",
"where",
"Laravel",
"was",
"double",
"casting",
"the",
"outputs",
".",
"I",
"m",
"not",
"sure",
"why",
"this",
"was",
"happening",
"after",
"some",
"length... | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Models/Encoding.php#L360-L372 | train |
BKWLD/decoy | classes/Markup/ImageElement.php | ImageElement.render | public function render()
{
// Different conditions for different types of tags
switch ($this->element) {
// Img tags use the src
case 'img':
if (empty($this->getAttribute('src'))) {
return '';
}
break;
// Divs have the image as a background-image
// https://regex101.com/r/eF0oD0/1
default:
if (!preg_match('#background-image:\s*url\([\'"]?[\w\/]#',
$this->getAttribute('style'))) {
return '';
}
}
// Carry on with normal rendering
return parent::render();
} | php | public function render()
{
// Different conditions for different types of tags
switch ($this->element) {
// Img tags use the src
case 'img':
if (empty($this->getAttribute('src'))) {
return '';
}
break;
// Divs have the image as a background-image
// https://regex101.com/r/eF0oD0/1
default:
if (!preg_match('#background-image:\s*url\([\'"]?[\w\/]#',
$this->getAttribute('style'))) {
return '';
}
}
// Carry on with normal rendering
return parent::render();
} | [
"public",
"function",
"render",
"(",
")",
"{",
"// Different conditions for different types of tags",
"switch",
"(",
"$",
"this",
"->",
"element",
")",
"{",
"// Img tags use the src",
"case",
"'img'",
":",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"getAttribute"... | Check that an image URL exists before allowing the tag to render
@return string | [
"Check",
"that",
"an",
"image",
"URL",
"exists",
"before",
"allowing",
"the",
"tag",
"to",
"render"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Markup/ImageElement.php#L30-L53 | train |
BKWLD/decoy | classes/Routing/UrlGenerator.php | UrlGenerator.relative | public function relative($action = 'index', $id = null, $child = null)
{
// Get the current path, adding a leading slash that should be missing
$path = '/'.$this->path;
// Get the URL up to and including the last controller. If we're not linking
// to a child, also remove the id, which may be replaced by a passed id
$actions = implode('|', $this->actions);
if ($child) {
$pattern = '#(/('.$actions.'))?/?$#';
} else {
$pattern = '#(/\d+)?(/('.$actions.'))?/?$#';
}
$path = preg_replace($pattern, '', $path);
// If there is an id and we're not linking to a child, add that id
if (!$child && $id) {
$path .= '/'.$id;
}
// If there is a child controller, add that now
if ($child) {
// If the child has a backslash, it's a namespaced class name, so convert to just name
if (strpos($child, '\\') !== false) {
$child = $this->slugController($child);
}
// If currently on an edit view (where we always respect child parameters literally),
// or if the link is to an index view (for many to many to self) or if the child
// is different than the current path, appened the child controller slug.
if (preg_match('#edit$#', $this->path)
|| $action == 'index'
|| !preg_match('#'.$child.'(/\d+)?$#', $path)
) {
$path .= '/'.$child;
}
// If the action was not index and there was an id, add it
if ($action != 'index' && $id) {
$path .= '/'.$id;
}
}
// Now, add actions (except for index, which is implied by the lack of an action)
if ($action && $action != 'index') {
$path .= '/'.$action;
}
// Done, return it
return $path;
} | php | public function relative($action = 'index', $id = null, $child = null)
{
// Get the current path, adding a leading slash that should be missing
$path = '/'.$this->path;
// Get the URL up to and including the last controller. If we're not linking
// to a child, also remove the id, which may be replaced by a passed id
$actions = implode('|', $this->actions);
if ($child) {
$pattern = '#(/('.$actions.'))?/?$#';
} else {
$pattern = '#(/\d+)?(/('.$actions.'))?/?$#';
}
$path = preg_replace($pattern, '', $path);
// If there is an id and we're not linking to a child, add that id
if (!$child && $id) {
$path .= '/'.$id;
}
// If there is a child controller, add that now
if ($child) {
// If the child has a backslash, it's a namespaced class name, so convert to just name
if (strpos($child, '\\') !== false) {
$child = $this->slugController($child);
}
// If currently on an edit view (where we always respect child parameters literally),
// or if the link is to an index view (for many to many to self) or if the child
// is different than the current path, appened the child controller slug.
if (preg_match('#edit$#', $this->path)
|| $action == 'index'
|| !preg_match('#'.$child.'(/\d+)?$#', $path)
) {
$path .= '/'.$child;
}
// If the action was not index and there was an id, add it
if ($action != 'index' && $id) {
$path .= '/'.$id;
}
}
// Now, add actions (except for index, which is implied by the lack of an action)
if ($action && $action != 'index') {
$path .= '/'.$action;
}
// Done, return it
return $path;
} | [
"public",
"function",
"relative",
"(",
"$",
"action",
"=",
"'index'",
",",
"$",
"id",
"=",
"null",
",",
"$",
"child",
"=",
"null",
")",
"{",
"// Get the current path, adding a leading slash that should be missing",
"$",
"path",
"=",
"'/'",
".",
"$",
"this",
"-... | Construct a route that takes into account the current url path as well
as the function arguments
@param string $action The action we're linking to: index/edit/etc
@param integer $id Optional id that we're linking to. Required for actions like edit.
@param string $child The name (or full class) of a child controller
of the current path: 'slides', 'Admin\SlidesController'
@return string '/admin/articles' | [
"Construct",
"a",
"route",
"that",
"takes",
"into",
"account",
"the",
"current",
"url",
"path",
"as",
"well",
"as",
"the",
"function",
"arguments"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Routing/UrlGenerator.php#L49-L100 | train |
BKWLD/decoy | classes/Routing/UrlGenerator.php | UrlGenerator.action | public function action($controller = null, $id = null)
{
// Assume that the current, first path segment is the directory decoy is
// running in
preg_match('#[a-z-]+#i', $this->path, $matches);
$decoy = $matches[0];
// Strip the action from the controller
$action = '';
if (preg_match('#@\w+$#', $controller, $matches)) {
$action = substr($matches[0], 1);
$controller = substr($controller, 0, -strlen($matches[0]));
}
// Convert controller for URL
$controller = $this->slugController($controller);
// Begin the url
$path = '/'.$decoy.'/'.$controller;
// If there is an id, add it now
if ($id) {
$path .= '/'.$id;
}
// Now, add actions (except for index, which is implied by the lack of an action)
if ($action && $action != 'index') {
$path .= '/'.$action;
}
// Done, return it
return $path;
} | php | public function action($controller = null, $id = null)
{
// Assume that the current, first path segment is the directory decoy is
// running in
preg_match('#[a-z-]+#i', $this->path, $matches);
$decoy = $matches[0];
// Strip the action from the controller
$action = '';
if (preg_match('#@\w+$#', $controller, $matches)) {
$action = substr($matches[0], 1);
$controller = substr($controller, 0, -strlen($matches[0]));
}
// Convert controller for URL
$controller = $this->slugController($controller);
// Begin the url
$path = '/'.$decoy.'/'.$controller;
// If there is an id, add it now
if ($id) {
$path .= '/'.$id;
}
// Now, add actions (except for index, which is implied by the lack of an action)
if ($action && $action != 'index') {
$path .= '/'.$action;
}
// Done, return it
return $path;
} | [
"public",
"function",
"action",
"(",
"$",
"controller",
"=",
"null",
",",
"$",
"id",
"=",
"null",
")",
"{",
"// Assume that the current, first path segment is the directory decoy is",
"// running in",
"preg_match",
"(",
"'#[a-z-]+#i'",
",",
"$",
"this",
"->",
"path",
... | Make a URL given a fully namespaced controller. This only generates routes
as if the controller is in the root level; as if it has no parents.
@param string $controller ex: Bkwld\Decoy\Controllers\Admins@create
@param integer $id
@return string ex: http://admin/admins/create | [
"Make",
"a",
"URL",
"given",
"a",
"fully",
"namespaced",
"controller",
".",
"This",
"only",
"generates",
"routes",
"as",
"if",
"the",
"controller",
"is",
"in",
"the",
"root",
"level",
";",
"as",
"if",
"it",
"has",
"no",
"parents",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Routing/UrlGenerator.php#L110-L142 | train |
BKWLD/decoy | classes/Routing/UrlGenerator.php | UrlGenerator.slugController | public function slugController($controller)
{
// Get the controller name
$controller = preg_replace('#^('.preg_quote('Bkwld\Decoy\Controllers\\')
.'|'.preg_quote('App\Http\Controllers\Admin\\').')#', '', $controller);
// Convert study caps to dashes
$controller = Str::snake($controller, '-');
// Done
return $controller;
} | php | public function slugController($controller)
{
// Get the controller name
$controller = preg_replace('#^('.preg_quote('Bkwld\Decoy\Controllers\\')
.'|'.preg_quote('App\Http\Controllers\Admin\\').')#', '', $controller);
// Convert study caps to dashes
$controller = Str::snake($controller, '-');
// Done
return $controller;
} | [
"public",
"function",
"slugController",
"(",
"$",
"controller",
")",
"{",
"// Get the controller name",
"$",
"controller",
"=",
"preg_replace",
"(",
"'#^('",
".",
"preg_quote",
"(",
"'Bkwld\\Decoy\\Controllers\\\\'",
")",
".",
"'|'",
".",
"preg_quote",
"(",
"'App\\H... | Convert a controller to how it is referenced in a url
@param string $controller ex: Admin\ArticlesAreCoolController
@return string ex: articles-are-cool | [
"Convert",
"a",
"controller",
"to",
"how",
"it",
"is",
"referenced",
"in",
"a",
"url"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Routing/UrlGenerator.php#L150-L161 | train |
BKWLD/decoy | classes/Observers/Changes.php | Changes.handle | public function handle($event, $payload)
{
list($model) = $payload;
// Don't log changes to pivot models. Even though a user may have initiated
// this, it's kind of meaningless to them. These events can happen when a
// user messes with drag and drop positioning.
if (is_a($model, \Illuminate\Database\Eloquent\Relations\Pivot::class)) {
return;
}
// Get the action of the event
preg_match('#eloquent\.(\w+)#', $event, $matches);
$action = $matches[1];
if (!in_array($action, $this->supported)) {
return;
}
// Get the admin acting on the record
$admin = app('decoy.user');
// If `log_changes` was configed as a callable, see if this model event
// should not be logged
if ($check = config('decoy.site.log_changes')) {
if (is_bool($check) && !$check) {
return;
}
if (is_callable($check)) {
\Log::error('Callable log_changes have been deprecated');
if (!call_user_func($check, $model, $action, $admin)) {
return;
}
}
} else {
return;
}
// Check with the model itself to see if it should be logged
if (method_exists($model, 'shouldLogChange')) {
if (!$model->shouldLogChange($action)) {
return;
}
// Default to not logging changes if there is no shouldLogChange()
} else {
return;
}
// Log the event
Change::log($model, $action, $admin);
} | php | public function handle($event, $payload)
{
list($model) = $payload;
// Don't log changes to pivot models. Even though a user may have initiated
// this, it's kind of meaningless to them. These events can happen when a
// user messes with drag and drop positioning.
if (is_a($model, \Illuminate\Database\Eloquent\Relations\Pivot::class)) {
return;
}
// Get the action of the event
preg_match('#eloquent\.(\w+)#', $event, $matches);
$action = $matches[1];
if (!in_array($action, $this->supported)) {
return;
}
// Get the admin acting on the record
$admin = app('decoy.user');
// If `log_changes` was configed as a callable, see if this model event
// should not be logged
if ($check = config('decoy.site.log_changes')) {
if (is_bool($check) && !$check) {
return;
}
if (is_callable($check)) {
\Log::error('Callable log_changes have been deprecated');
if (!call_user_func($check, $model, $action, $admin)) {
return;
}
}
} else {
return;
}
// Check with the model itself to see if it should be logged
if (method_exists($model, 'shouldLogChange')) {
if (!$model->shouldLogChange($action)) {
return;
}
// Default to not logging changes if there is no shouldLogChange()
} else {
return;
}
// Log the event
Change::log($model, $action, $admin);
} | [
"public",
"function",
"handle",
"(",
"$",
"event",
",",
"$",
"payload",
")",
"{",
"list",
"(",
"$",
"model",
")",
"=",
"$",
"payload",
";",
"// Don't log changes to pivot models. Even though a user may have initiated",
"// this, it's kind of meaningless to them. These eve... | Handle all Eloquent model events
@param string $event
@param array $payload Contains:
- Bkwld\Decoy\Models\Base $model | [
"Handle",
"all",
"Eloquent",
"model",
"events"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Observers/Changes.php#L30-L80 | train |
BKWLD/decoy | classes/Layout/Breadcrumbs.php | Breadcrumbs.parseURL | public function parseURL()
{
$breadcrumbs = [];
// Get the segments
$path = Request::path();
$segments = explode('/', $path);
// Loop through them in blocks of 2: [list, detail]
$url = $segments[0];
for ($i=1; $i<count($segments); $i+=2) {
// If an action URL, you're at the end of the URL
if (in_array($segments[$i], ['edit'])) {
break;
}
// Figure out the controller given the url partial
$url .= '/' . $segments[$i];
$router = new Wildcard($segments[0], 'GET', $url);
if (!($controller = $router->detectController())) {
continue;
}
$controller = new $controller;
// Add controller to breadcrumbs
$breadcrumbs[URL::to($url)] = strip_tags($controller->title(), '<img>');
// Add a detail if it exists
if (!isset($segments[$i+1])) {
break;
}
$id = $segments[$i+1];
// On a "new" page
if ($id == 'create') {
$url .= '/' . $id;
$breadcrumbs[URL::to($url)] = __('decoy::breadcrumbs.new');
// On an edit page
} elseif (is_numeric($id)) {
$url .= '/' . $id;
$item = $this->find($controller, $id);
$title = $item->getAdminTitleAttribute();
$breadcrumbs[URL::to($url.'/edit')] = $title;
}
}
// Return the full list
return $breadcrumbs;
} | php | public function parseURL()
{
$breadcrumbs = [];
// Get the segments
$path = Request::path();
$segments = explode('/', $path);
// Loop through them in blocks of 2: [list, detail]
$url = $segments[0];
for ($i=1; $i<count($segments); $i+=2) {
// If an action URL, you're at the end of the URL
if (in_array($segments[$i], ['edit'])) {
break;
}
// Figure out the controller given the url partial
$url .= '/' . $segments[$i];
$router = new Wildcard($segments[0], 'GET', $url);
if (!($controller = $router->detectController())) {
continue;
}
$controller = new $controller;
// Add controller to breadcrumbs
$breadcrumbs[URL::to($url)] = strip_tags($controller->title(), '<img>');
// Add a detail if it exists
if (!isset($segments[$i+1])) {
break;
}
$id = $segments[$i+1];
// On a "new" page
if ($id == 'create') {
$url .= '/' . $id;
$breadcrumbs[URL::to($url)] = __('decoy::breadcrumbs.new');
// On an edit page
} elseif (is_numeric($id)) {
$url .= '/' . $id;
$item = $this->find($controller, $id);
$title = $item->getAdminTitleAttribute();
$breadcrumbs[URL::to($url.'/edit')] = $title;
}
}
// Return the full list
return $breadcrumbs;
} | [
"public",
"function",
"parseURL",
"(",
")",
"{",
"$",
"breadcrumbs",
"=",
"[",
"]",
";",
"// Get the segments",
"$",
"path",
"=",
"Request",
"::",
"path",
"(",
")",
";",
"$",
"segments",
"=",
"explode",
"(",
"'/'",
",",
"$",
"path",
")",
";",
"// Loo... | Step through the URL, creating controller and model objects for relevant
segments to populate richer data in the breadcrumbs, automatically
@return array | [
"Step",
"through",
"the",
"URL",
"creating",
"controller",
"and",
"model",
"objects",
"for",
"relevant",
"segments",
"to",
"populate",
"richer",
"data",
"in",
"the",
"breadcrumbs",
"automatically"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Layout/Breadcrumbs.php#L50-L100 | train |
BKWLD/decoy | classes/Layout/Breadcrumbs.php | Breadcrumbs.find | public function find($controller, $id)
{
$model = $controller->model();
if ($controller->withTrashed()) {
return $model::withTrashed()->find($id);
} else {
return $model::find($id);
}
} | php | public function find($controller, $id)
{
$model = $controller->model();
if ($controller->withTrashed()) {
return $model::withTrashed()->find($id);
} else {
return $model::find($id);
}
} | [
"public",
"function",
"find",
"(",
"$",
"controller",
",",
"$",
"id",
")",
"{",
"$",
"model",
"=",
"$",
"controller",
"->",
"model",
"(",
")",
";",
"if",
"(",
"$",
"controller",
"->",
"withTrashed",
"(",
")",
")",
"{",
"return",
"$",
"model",
"::",... | Lookup a model instance given the controller and id, including any
trashed models in case the controller should show trashed models
@param Controller\Base $controller
@param integer $id
@return Model | [
"Lookup",
"a",
"model",
"instance",
"given",
"the",
"controller",
"and",
"id",
"including",
"any",
"trashed",
"models",
"in",
"case",
"the",
"controller",
"should",
"show",
"trashed",
"models"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Layout/Breadcrumbs.php#L110-L118 | train |
BKWLD/decoy | classes/Layout/Breadcrumbs.php | Breadcrumbs.back | public function back()
{
// If there aren't enough breadcrumbs for a back URL, report false
if (count($this->links) < 2) {
return;
}
// Get the URL from two back from the end in the breadcrumbs array
$urls = array_keys($this->links);
return $urls[count($urls) - 2];
} | php | public function back()
{
// If there aren't enough breadcrumbs for a back URL, report false
if (count($this->links) < 2) {
return;
}
// Get the URL from two back from the end in the breadcrumbs array
$urls = array_keys($this->links);
return $urls[count($urls) - 2];
} | [
"public",
"function",
"back",
"(",
")",
"{",
"// If there aren't enough breadcrumbs for a back URL, report false",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"links",
")",
"<",
"2",
")",
"{",
"return",
";",
"}",
"// Get the URL from two back from the end in the breadcr... | Get the url for a back button given a breadcrumbs array. Or return false
if there is no where to go back to.
@return string|void | [
"Get",
"the",
"url",
"for",
"a",
"back",
"button",
"given",
"a",
"breadcrumbs",
"array",
".",
"Or",
"return",
"false",
"if",
"there",
"is",
"no",
"where",
"to",
"go",
"back",
"to",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Layout/Breadcrumbs.php#L146-L158 | train |
BKWLD/decoy | classes/Layout/Breadcrumbs.php | Breadcrumbs.smartBack | public function smartBack()
{
// If we are on a listing page (an odd length), do the normal stuff
// http://stackoverflow.com/a/9153969/59160
if (count($this->links) & 1) {
return $this->back();
}
// If we're on the first level detail page, do normal stuff
if (count($this->links) === 2) {
return $this->back();
}
// Otherwise, skip the previous (the listing) and go direct to the previous detail
$urls = array_keys($this->links);
return $urls[count($urls) - 3];
} | php | public function smartBack()
{
// If we are on a listing page (an odd length), do the normal stuff
// http://stackoverflow.com/a/9153969/59160
if (count($this->links) & 1) {
return $this->back();
}
// If we're on the first level detail page, do normal stuff
if (count($this->links) === 2) {
return $this->back();
}
// Otherwise, skip the previous (the listing) and go direct to the previous detail
$urls = array_keys($this->links);
return $urls[count($urls) - 3];
} | [
"public",
"function",
"smartBack",
"(",
")",
"{",
"// If we are on a listing page (an odd length), do the normal stuff",
"// http://stackoverflow.com/a/9153969/59160",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"links",
")",
"&",
"1",
")",
"{",
"return",
"$",
"this",
... | If hitting back from a child detail page, goes to the parent detail page
rather than to the child listing page. For instance, if you are editing
the slides of a news page, when you go "back", it's back to the news page
and not the listing of the news slides
@return string | [
"If",
"hitting",
"back",
"from",
"a",
"child",
"detail",
"page",
"goes",
"to",
"the",
"parent",
"detail",
"page",
"rather",
"than",
"to",
"the",
"child",
"listing",
"page",
".",
"For",
"instance",
"if",
"you",
"are",
"editing",
"the",
"slides",
"of",
"a"... | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Layout/Breadcrumbs.php#L168-L186 | train |
BKWLD/decoy | classes/Input/EncodingProviders/Zencoder.php | Zencoder.encode | public function encode($source, $preset)
{
// Tell the Zencoder SDK to create a job
try {
$outputs = $this->outputsConfig($preset);
$job = $this->sdk()->jobs->create([
'input' => $source,
'output' => $outputs,
]);
// Store the response from the SDK
$this->model->storeJob($job->id, $this->outputsToHash($job->outputs));
// Report an error with the encode
} catch (Services_Zencoder_Exception $e) {
$this->model->status('error', implode(' ', $this->zencoderArray($e->getErrors())));
} catch (Exception $e) {
$this->model->status('error', $e->getMessage());
}
} | php | public function encode($source, $preset)
{
// Tell the Zencoder SDK to create a job
try {
$outputs = $this->outputsConfig($preset);
$job = $this->sdk()->jobs->create([
'input' => $source,
'output' => $outputs,
]);
// Store the response from the SDK
$this->model->storeJob($job->id, $this->outputsToHash($job->outputs));
// Report an error with the encode
} catch (Services_Zencoder_Exception $e) {
$this->model->status('error', implode(' ', $this->zencoderArray($e->getErrors())));
} catch (Exception $e) {
$this->model->status('error', $e->getMessage());
}
} | [
"public",
"function",
"encode",
"(",
"$",
"source",
",",
"$",
"preset",
")",
"{",
"// Tell the Zencoder SDK to create a job",
"try",
"{",
"$",
"outputs",
"=",
"$",
"this",
"->",
"outputsConfig",
"(",
"$",
"preset",
")",
";",
"$",
"job",
"=",
"$",
"this",
... | Tell the service to encode an asset it's source
@param string $source A full URL for the source asset
@param string $preset The key to the preset function
@return void | [
"Tell",
"the",
"service",
"to",
"encode",
"an",
"asset",
"it",
"s",
"source"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/EncodingProviders/Zencoder.php#L58-L77 | train |
BKWLD/decoy | classes/Input/EncodingProviders/Zencoder.php | Zencoder.filterHLS | protected function filterHLS($config)
{
// Do not allow any outputs that have a type of "segmented" or "playlist"
if (empty($config['playlist'])) {
return array_filter($config, function ($output) {
return !(isset($output['type']) && in_array($output['type'], ['segmented', 'playlist']));
});
}
// Else, passthrough the config
return $config;
} | php | protected function filterHLS($config)
{
// Do not allow any outputs that have a type of "segmented" or "playlist"
if (empty($config['playlist'])) {
return array_filter($config, function ($output) {
return !(isset($output['type']) && in_array($output['type'], ['segmented', 'playlist']));
});
}
// Else, passthrough the config
return $config;
} | [
"protected",
"function",
"filterHLS",
"(",
"$",
"config",
")",
"{",
"// Do not allow any outputs that have a type of \"segmented\" or \"playlist\"",
"if",
"(",
"empty",
"(",
"$",
"config",
"[",
"'playlist'",
"]",
")",
")",
"{",
"return",
"array_filter",
"(",
"$",
"c... | If the playlist is set to `false` then remove all the HLS encodings. HLS
is the "http live streaming" outputs that let us serve a video that can adjust
quality levels in response to the bandwidth of the clietn. Works only on iPhone,
Android, and Safari right now.
@param array $config A config assoc array
@return array | [
"If",
"the",
"playlist",
"is",
"set",
"to",
"false",
"then",
"remove",
"all",
"the",
"HLS",
"encodings",
".",
"HLS",
"is",
"the",
"http",
"live",
"streaming",
"outputs",
"that",
"let",
"us",
"serve",
"a",
"video",
"that",
"can",
"adjust",
"quality",
"lev... | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/EncodingProviders/Zencoder.php#L104-L115 | train |
BKWLD/decoy | classes/Input/EncodingProviders/Zencoder.php | Zencoder.addCommonProps | protected function addCommonProps($outputs)
{
// Decoy settings
$common = [
// Destination location as a directory
'base_url' => $this->destination(),
// Register for notifications for when the conding is done. If testing
// from CLI, just set the app.url config to a ngork domain.
'notifications' => [route('decoy::encode@notify')],
];
// Apply common settings ontop of the passed config
foreach ($outputs as $label => &$config) {
$common['label'] = $label;
// Make the filename from the label
$common['filename'] = $label.'.'.$config['format'];
// Do the merge
$config = array_merge($common, $config);
}
// Strip the keys from the array at this point, Zencoder doesn't like them
return array_values($outputs);
} | php | protected function addCommonProps($outputs)
{
// Decoy settings
$common = [
// Destination location as a directory
'base_url' => $this->destination(),
// Register for notifications for when the conding is done. If testing
// from CLI, just set the app.url config to a ngork domain.
'notifications' => [route('decoy::encode@notify')],
];
// Apply common settings ontop of the passed config
foreach ($outputs as $label => &$config) {
$common['label'] = $label;
// Make the filename from the label
$common['filename'] = $label.'.'.$config['format'];
// Do the merge
$config = array_merge($common, $config);
}
// Strip the keys from the array at this point, Zencoder doesn't like them
return array_values($outputs);
} | [
"protected",
"function",
"addCommonProps",
"(",
"$",
"outputs",
")",
"{",
"// Decoy settings",
"$",
"common",
"=",
"[",
"// Destination location as a directory",
"'base_url'",
"=>",
"$",
"this",
"->",
"destination",
"(",
")",
",",
"// Register for notifications for when... | Update the config with properties that are common to all outputs
@param array $config
@return array | [
"Update",
"the",
"config",
"with",
"properties",
"that",
"are",
"common",
"to",
"all",
"outputs"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/EncodingProviders/Zencoder.php#L123-L150 | train |
BKWLD/decoy | classes/Input/EncodingProviders/Zencoder.php | Zencoder.outputsToHash | protected function outputsToHash($outputs)
{
return array_map(function ($output) {
// If a destination_root was set, subsitute that in for the destination
// in the retured URL
if ($root = Config::get('decoy.encode.destination_root')) {
return str_replace(Config::get('decoy.encode.destination'), $root, $output->url);
}
// Else just return the URL
return $output->url;
}, $this->zencoderArray($outputs));
} | php | protected function outputsToHash($outputs)
{
return array_map(function ($output) {
// If a destination_root was set, subsitute that in for the destination
// in the retured URL
if ($root = Config::get('decoy.encode.destination_root')) {
return str_replace(Config::get('decoy.encode.destination'), $root, $output->url);
}
// Else just return the URL
return $output->url;
}, $this->zencoderArray($outputs));
} | [
"protected",
"function",
"outputsToHash",
"(",
"$",
"outputs",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"$",
"output",
")",
"{",
"// If a destination_root was set, subsitute that in for the destination",
"// in the retured URL",
"if",
"(",
"$",
"root",
"="... | Massage the outputs from Zencoder into a key-val associative array
@param array $outputs
@return array | [
"Massage",
"the",
"outputs",
"from",
"Zencoder",
"into",
"a",
"key",
"-",
"val",
"associative",
"array"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/EncodingProviders/Zencoder.php#L158-L171 | train |
BKWLD/decoy | classes/Input/EncodingProviders/Zencoder.php | Zencoder.handleNotification | public function handleNotification($input)
{
// Parse the input
$job = $this->sdk()->notifications->parseIncoming()->job;
// Find the encoding model instance. If it's not found, then just
// ignore it. This can easily happen if someone replaces a video
// while one is being uploaded.
if (!$model = Encoding::where('job_id', '=', $job->id)->first()) {
return;
}
// Loop through the jobs and look for error messages. A job may recieve a
// seperate notification for each output that has failed though the job
// is still processessing.
$errors = trim(implode(' ', array_map(function ($output) {
return isset($output->error_message) ? '(Output '.$output->label.') '.$output->error_message : null;
}, $this->zencoderArray($job->outputs))));
// If there were any messages, treat the job as errored. This also tries
// to fix an issue I saw where a final "error" notifcation wasn't fired even
// though multiple jobs failed.
$state = empty($errors) ? $job->state : 'failed';
// Update the model
switch ($state) {
// Simple passthru of status
case 'processing':
case 'cancelled':
$model->status($job->state);
break;
// Massage name
case 'finished':
$model->response = $input;
$model->status('complete');
break;
// Find error messages on the output
case 'failed':
$model->status('error', $errors);
break;
// Default
default:
$model->status('error', 'Unkown Zencoder state: '.$job->state);
}
} | php | public function handleNotification($input)
{
// Parse the input
$job = $this->sdk()->notifications->parseIncoming()->job;
// Find the encoding model instance. If it's not found, then just
// ignore it. This can easily happen if someone replaces a video
// while one is being uploaded.
if (!$model = Encoding::where('job_id', '=', $job->id)->first()) {
return;
}
// Loop through the jobs and look for error messages. A job may recieve a
// seperate notification for each output that has failed though the job
// is still processessing.
$errors = trim(implode(' ', array_map(function ($output) {
return isset($output->error_message) ? '(Output '.$output->label.') '.$output->error_message : null;
}, $this->zencoderArray($job->outputs))));
// If there were any messages, treat the job as errored. This also tries
// to fix an issue I saw where a final "error" notifcation wasn't fired even
// though multiple jobs failed.
$state = empty($errors) ? $job->state : 'failed';
// Update the model
switch ($state) {
// Simple passthru of status
case 'processing':
case 'cancelled':
$model->status($job->state);
break;
// Massage name
case 'finished':
$model->response = $input;
$model->status('complete');
break;
// Find error messages on the output
case 'failed':
$model->status('error', $errors);
break;
// Default
default:
$model->status('error', 'Unkown Zencoder state: '.$job->state);
}
} | [
"public",
"function",
"handleNotification",
"(",
"$",
"input",
")",
"{",
"// Parse the input",
"$",
"job",
"=",
"$",
"this",
"->",
"sdk",
"(",
")",
"->",
"notifications",
"->",
"parseIncoming",
"(",
")",
"->",
"job",
";",
"// Find the encoding model instance. I... | Handle notification requests from the SDK
@param array $input Request::input()
@return mixed Reponse to the API | [
"Handle",
"notification",
"requests",
"from",
"the",
"SDK"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/EncodingProviders/Zencoder.php#L179-L227 | train |
BKWLD/decoy | classes/Input/EncodingProviders/Zencoder.php | Zencoder.progress | public function progress()
{
try {
$progress = $this->sdk()->jobs->progress($this->model->job_id);
if ($progress->state == 'finished') {
return 100;
}
return $progress->progress;
} catch (\Exception $e) {
return 0;
}
} | php | public function progress()
{
try {
$progress = $this->sdk()->jobs->progress($this->model->job_id);
if ($progress->state == 'finished') {
return 100;
}
return $progress->progress;
} catch (\Exception $e) {
return 0;
}
} | [
"public",
"function",
"progress",
"(",
")",
"{",
"try",
"{",
"$",
"progress",
"=",
"$",
"this",
"->",
"sdk",
"(",
")",
"->",
"jobs",
"->",
"progress",
"(",
"$",
"this",
"->",
"model",
"->",
"job_id",
")",
";",
"if",
"(",
"$",
"progress",
"->",
"s... | Return the encoding percentage as an int
@return int 0-100 | [
"Return",
"the",
"encoding",
"percentage",
"as",
"an",
"int"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/EncodingProviders/Zencoder.php#L234-L246 | train |
BKWLD/decoy | classes/Input/EncodingProviders/Zencoder.php | Zencoder.zencoderArray | public function zencoderArray($obj)
{
if (is_array($obj)) {
return $obj;
}
if (is_a($obj, 'Services_Zencoder_Object')) {
return get_object_vars($obj);
}
throw new Exception('Unexpected object: '.get_class($obj));
} | php | public function zencoderArray($obj)
{
if (is_array($obj)) {
return $obj;
}
if (is_a($obj, 'Services_Zencoder_Object')) {
return get_object_vars($obj);
}
throw new Exception('Unexpected object: '.get_class($obj));
} | [
"public",
"function",
"zencoderArray",
"(",
"$",
"obj",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"obj",
")",
")",
"{",
"return",
"$",
"obj",
";",
"}",
"if",
"(",
"is_a",
"(",
"$",
"obj",
",",
"'Services_Zencoder_Object'",
")",
")",
"{",
"return",
... | Convert a Services_Zencoder_Object object to an array
@param Services_Zencoder_Object|array $obj
@return array | [
"Convert",
"a",
"Services_Zencoder_Object",
"object",
"to",
"an",
"array"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Input/EncodingProviders/Zencoder.php#L264-L275 | train |
BKWLD/decoy | classes/Exceptions/Handler.php | Handler.handle404s | protected function handle404s($request, BaseException $e)
{
// Check for right exception
if (!is_a($e, ModelNotFoundException::class) && !is_a($e, NotFoundHttpException::class)) {
return;
}
// Check for a valid redirect
if ($rule = RedirectRule::matchUsingRequest()->first()) {
return redirect($rule->to, $rule->code);
}
// Return header only on AJAX
if ($request->ajax()) {
return response(null, 404);
}
} | php | protected function handle404s($request, BaseException $e)
{
// Check for right exception
if (!is_a($e, ModelNotFoundException::class) && !is_a($e, NotFoundHttpException::class)) {
return;
}
// Check for a valid redirect
if ($rule = RedirectRule::matchUsingRequest()->first()) {
return redirect($rule->to, $rule->code);
}
// Return header only on AJAX
if ($request->ajax()) {
return response(null, 404);
}
} | [
"protected",
"function",
"handle404s",
"(",
"$",
"request",
",",
"BaseException",
"$",
"e",
")",
"{",
"// Check for right exception",
"if",
"(",
"!",
"is_a",
"(",
"$",
"e",
",",
"ModelNotFoundException",
"::",
"class",
")",
"&&",
"!",
"is_a",
"(",
"$",
"e"... | If a 404 exception, check if there is a redirect rule. Or return a simple
header if an AJAX request.
@param \Illuminate\Http\Request $request
@param \Exception $e
@return \Illuminate\Http\RedirectResponse | [
"If",
"a",
"404",
"exception",
"check",
"if",
"there",
"is",
"a",
"redirect",
"rule",
".",
"Or",
"return",
"a",
"simple",
"header",
"if",
"an",
"AJAX",
"request",
"."
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Exceptions/Handler.php#L51-L67 | train |
BKWLD/decoy | classes/Exceptions/Handler.php | Handler.handleValidation | protected function handleValidation($request, BaseException $e)
{
if (!is_a($e, ValidationFail::class)) {
return;
}
// Log validation errors so Reporter will output them
// if (Config::get('app.debug')) Log::debug(print_r($e->validation->messages(), true));
// Respond
if ($request->ajax()) {
return response()->json($e->validation->messages(), 400);
}
return back()->withInput()->withErrors($e->validation);
} | php | protected function handleValidation($request, BaseException $e)
{
if (!is_a($e, ValidationFail::class)) {
return;
}
// Log validation errors so Reporter will output them
// if (Config::get('app.debug')) Log::debug(print_r($e->validation->messages(), true));
// Respond
if ($request->ajax()) {
return response()->json($e->validation->messages(), 400);
}
return back()->withInput()->withErrors($e->validation);
} | [
"protected",
"function",
"handleValidation",
"(",
"$",
"request",
",",
"BaseException",
"$",
"e",
")",
"{",
"if",
"(",
"!",
"is_a",
"(",
"$",
"e",
",",
"ValidationFail",
"::",
"class",
")",
")",
"{",
"return",
";",
"}",
"// Log validation errors so Reporter ... | Redirect users to the previous page with validation errors
@param \Illuminate\Http\Request $request
@param \Exception $e
@return \Illuminate\Http\Response | [
"Redirect",
"users",
"to",
"the",
"previous",
"page",
"with",
"validation",
"errors"
] | 7a4acfa8e00cdca7ef4d82672a6547bae61f8e73 | https://github.com/BKWLD/decoy/blob/7a4acfa8e00cdca7ef4d82672a6547bae61f8e73/classes/Exceptions/Handler.php#L91-L106 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.