public function update(ProfileUpdateRequest $request, $id)
    {
        $user = User::findOrFail($id);
        $user->fill($request->toArray())->save();
        $user->save();

        Session::put('_profile', trans('canvas::messages.update_success', ['entity' => 'Profile']));

        return redirect()->route('canvas.admin.profile.index');
    }

public function update ( ProfileUpdateRequest $ request , $ id ) { $ user = User :: findOrFail ( $ id ) ; $ user -> fill ( $ request -> toArray ( ) ) -> save ( ) ; $ user -> save ( ) ; Session :: put ( '_profile' , trans ( 'canvas::messages.update_success' , [ 'entity' => 'Profile' ] ) ) ; return redirect ( ) -> route ( 'canvas.admin.profile.index' ) ; }

Update the user profile information.

@param ProfileUpdateRequest $request
@param $id

@return \Illuminate\Http\RedirectResponse


public static function authenticated(Request $request, User $user)
    {
        // Get and record latest version.
        self::getLatestVersion();

        // Set login message.
        Session::put('_login', trans('canvas::messages.login', ['display_name' => $user->display_name]));
    }

public
static
function
authenticated
(
Request
$
request
,
User
$
user
)
{
// Get and record latest version.
self
::
getLatestVersion
(
)
;
// Set login message.
Session
::
put
(
'_login'
,
trans
(
'canvas::messages.login'
,
[
'display_name'
=>
$
user
->
display_name
]
)
)
;
}

Actions to be taken when user is successfully authenticated.

@param Request $request
@param User $user
@return void

Actions to be taken when user is successfully authenticated .


public static function getCurrentVersion($update = true)
    {
        $extMan = new ExtensionManager(resolve('app'), resolve('files'));
        $packageName = self::CORE_PACKAGE;
        $version = 'Unknown';

        // Retrieve framework (Easel) package info.
        $core = $extMan->getExtension(str_replace('/', '-', self::CORE_PACKAGE), ['canvas-framework']);
        $version = $core->getVersion();
        $dist = $core->__get('dist');
        if (substr($version, 0, 4) === 'dev-') {
            $version .= ' '.substr($dist['reference'], 0, 12);
        }

        // Save to Canvas Settings
        if ($update) {
            $setting = Settings::updateOrCreate(
                ['setting_name' => 'canvas_version'],
                ['setting_value' => $version]
            );
        }

        return $version;
    }

Get the currently installed version of Canvas.

@param bool $update If set to true, latest version in DB will be updated.
@return string

Get the currently installed version of Canvas .


public function postFillData()
    {
        return [
            'user_id' => $this->user_id,
            'title' => $this->title,
            'slug' => $this->slug,
            'subtitle' => $this->subtitle,
            'page_image' => $this->page_image,
            'content_raw' => $this->get('content'),
            'meta_description' => $this->meta_description,
            'is_published' => (bool) $this->is_published,
            'published_at' => $this->published_at,
            'layout' => config('blog.post_layout'),
        ];
    }

public function postFillData ( ) { return [ 'user_id' => $ this -> user_id , 'title' => $ this -> title , 'slug' => $ this -> slug , 'subtitle' => $ this -> subtitle , 'page_image' => $ this -> page_image , 'content_raw' => $ this -> get ( 'content' ) , 'meta_description' => $ this -> meta_description , 'is_published' => ( bool ) $ this -> is_published , 'published_at' => $ this -> published_at , 'layout' => config ( 'blog.post_layout' ) , ] ; }

Return the fields and values to create a new post from.

Return the fields and values to create a new post from .


public function enable($name)
    {
        if (! $this->isEnabled($name)) {
            $extension = $this->getExtension($name);

            $enabled = $this->getEnabled();

            $enabled[] = $name;

            $this->migrate($extension);

            $this->publishAssets($extension);

            $this->setEnabled($enabled);

            $extension->setEnabled(true);
        }
    }

public function enable ( $ name ) { if ( ! $ this -> isEnabled ( $ name ) ) { $ extension = $ this -> getExtension ( $ name ) ; $ enabled = $ this -> getEnabled ( ) ; $ enabled [ ] = $ name ; $ this -> migrate ( $ extension ) ; $ this -> publishAssets ( $ extension ) ; $ this -> setEnabled ( $ enabled ) ; $ extension -> setEnabled ( true ) ; } }

Enables the extension.

@param string $name


public function disable($name)
    {
        $enabled = $this->getEnabled();

        if (($k = array_search($name, $enabled)) !== false) {
            unset($enabled[$k]);

            $extension = $this->getExtension($name);

            $this->setEnabled($enabled);

            $extension->setEnabled(false);
        }
    }

public function disable ( $ name ) { $ enabled = $ this -> getEnabled ( ) ; if ( ( $ k = array_search ( $ name , $ enabled ) ) !== false ) { unset ( $ enabled [ $ k ] ) ; $ extension = $ this -> getExtension ( $ name ) ; $ this -> setEnabled ( $ enabled ) ; $ extension -> setEnabled ( false ) ; } }

Disables an extension.

@param string $name


public function uninstall($name)
    {
        $extension = $this->getExtension($name);

        $this->disable($name);

        $this->migrateDown($extension);

        $this->unpublishAssets($extension);

        $extension->setInstalled(false);
    }

public function uninstall ( $ name ) { $ extension = $ this -> getExtension ( $ name ) ; $ this -> disable ( $ name ) ; $ this -> migrateDown ( $ extension ) ; $ this -> unpublishAssets ( $ extension ) ; $ extension -> setInstalled ( false ) ; }

Uninstalls an extension.

@param string $name


public function migrate(Extension $extension, $up = true)
    {
        if ($extension->hasMigrations()) {
            $migrationDir = $extension->getPath().'/migrations';

            $this->app->bind('Illuminate\Database\Schema\Builder', function ($container) {
                return $container->make('Illuminate\Database\ConnectionInterface')->getSchemaBuilder();
            });

            if ($up) {
                $this->migrator->run($migrationDir, $extension);
            } else {
                $this->migrator->reset($migrationDir, $extension);
            }
        }
    }

Runs the database migrations for the extension.

@param Extension $extension
@param bool|true $up

Runs the database migrations for the extension .


public function getEnabledBootstrappers()
    {
        $bootstrappers = new Collection;

        foreach ($this->getEnabledExtensions() as $extension) {
            if ($this->filesystem->exists($file = $extension->getPath().'/bootstrap.php')) {
                $bootstrappers->push($file);
            }
        }

        return $bootstrappers;
    }

public function getEnabledBootstrappers ( ) { $ bootstrappers = new Collection ; foreach ( $ this -> getEnabledExtensions ( ) as $ extension ) { if ( $ this -> filesystem -> exists ( $ file = $ extension -> getPath ( ) . '/bootstrap.php' ) ) { $ bootstrappers -> push ( $ file ) ; } } return $ bootstrappers ; }

Loads all bootstrap.php files of the enabled extensions.

@return Collection

Loads all bootstrap . php files of the enabled extensions .


public function sanitiseInput()
    {
        $source = $this->getInputSource();

        $data = $source->all();

        $data['post_is_published_default'] = filter_var(
            $this->post_is_published_default,
            FILTER_VALIDATE_BOOLEAN
        );

        $source->replace($data);
    }

public function sanitiseInput ( ) { $ source = $ this -> getInputSource ( ) ; $ data = $ source -> all ( ) ; $ data [ 'post_is_published_default' ] = filter_var ( $ this -> post_is_published_default , FILTER_VALIDATE_BOOLEAN ) ; $ source -> replace ( $ data ) ; }

Sanitise the input from the request.
In this case, the input is type casted where required.

@return void

Sanitise the input from the request . In this case the input is type casted where required .


public function index()
    {
        $data = [
            'posts' => Post::all(),
            'recentPosts' => Post::orderBy('created_at', 'desc')->take(4)->get(),
            'tags' => Tag::all(),
            'users' => User::all(),
            'disqus' => Settings::disqus(),
            'analytics' => Settings::gaId(),
            'status' => App::isDownForMaintenance() ? CanvasHelper::MAINTENANCE_MODE_ENABLED : CanvasHelper::MAINTENANCE_MODE_DISABLED,
            'canvasVersion' => Settings::canvasVersion(),
            'latestRelease' => Settings::latestRelease(),
        ];

        return view('canvas::backend.home.index', compact('data'));
    }

public function index ( ) { $ data = [ 'posts' => Post :: all ( ) , 'recentPosts' => Post :: orderBy ( 'created_at' , 'desc' ) -> take ( 4 ) -> get ( ) , 'tags' => Tag :: all ( ) , 'users' => User :: all ( ) , 'disqus' => Settings :: disqus ( ) , 'analytics' => Settings :: gaId ( ) , 'status' => App :: isDownForMaintenance ( ) ? CanvasHelper :: MAINTENANCE_MODE_ENABLED : CanvasHelper :: MAINTENANCE_MODE_DISABLED , 'canvasVersion' => Settings :: canvasVersion ( ) , 'latestRelease' => Settings :: latestRelease ( ) , ] ; return view ( 'canvas::backend.home.index' , compact ( 'data' ) ) ; }

Display the application home page.

@return \Illuminate\View\View


protected function fieldsFromModel($id, array $fields)
    {
        $post = Post::findOrFail($id);
        $fieldNames = array_keys(array_except($fields, ['tags']));
        $fields = ['id' => $id];
        foreach ($fieldNames as $field) {
            $fields[$field] = $post->{$field};
        }
        $fields['tags'] = $post->tags()->pluck('tag')->all();

        return $fields;
    }

protected function fieldsFromModel ( $ id , array $ fields ) { $ post = Post :: findOrFail ( $ id ) ; $ fieldNames = array_keys ( array_except ( $ fields , [ 'tags' ] ) ) ; $ fields = [ 'id' => $ id ] ; foreach ( $ fieldNames as $ field ) { $ fields [ $ field ] = $ post -> { $ field } ; } $ fields [ 'tags' ] = $ post -> tags ( ) -> pluck ( 'tag' ) -> all ( ) ; return $ fields ; }

Return the field values from the model.

@param int $id
@param array $fields
@return array

Return the field values from the model .


protected function tagIndexData($tag)
    {
        $tag = Tag::where('tag', $tag)->firstOrFail();

        $reverse_direction = (bool) $tag->reverse_direction;

        $posts = Post::where('published_at', '<=', Carbon::now())
            ->whereHas('tags', function ($q) use ($tag) {
                $q->where('id', '=', $tag->id);
            })
            ->where('is_published', 1)
            ->orderBy('published_at', $reverse_direction ? 'asc' : 'desc')
            ->simplePaginate(config('blog.posts_per_page'));

        $posts->appends('tag', $tag->tag);

        $page_image = $tag->page_image ?: config('blog.page_image');

        return [
            'title' => $tag->title,
            'subtitle' => $tag->subtitle,
            'posts' => $posts,
            'page_image' => $page_image,
            'tag' => $tag,
            'reverse_direction' => $reverse_direction,
            'meta_description' => $tag->meta_description ?: \
            Settings::where('setting_name', 'blog_description')->find(1),
        ];
    }

protected function tagIndexData ( $ tag ) { $ tag = Tag :: where ( 'tag' , $ tag ) -> firstOrFail ( ) ; $ reverse_direction = ( bool ) $ tag -> reverse_direction ; $ posts = Post :: where ( 'published_at' , '<=' , Carbon :: now ( ) ) -> whereHas ( 'tags' , function ( $ q ) use ( $ tag ) { $ q -> where ( 'id' , '=' , $ tag -> id ) ; } ) -> where ( 'is_published' , 1 ) -> orderBy ( 'published_at' , $ reverse_direction ? 'asc' : 'desc' ) -> simplePaginate ( config ( 'blog.posts_per_page' ) ) ; $ posts -> appends ( 'tag' , $ tag -> tag ) ; $ page_image = $ tag -> page_image ? : config ( 'blog.page_image' ) ; return [ 'title' => $ tag -> title , 'subtitle' => $ tag -> subtitle , 'posts' => $ posts , 'page_image' => $ page_image , 'tag' => $ tag , 'reverse_direction' => $ reverse_direction , 'meta_description' => $ tag -> meta_description ? : \ Settings :: where ( 'setting_name' , 'blog_description' ) -> find ( 1 ) , ] ; }

Return data for a tag index page.

@param string $tag
@return array


protected function normalIndexData()
    {
        $posts = Post::with('tags')
            ->where('published_at', '<=', Carbon::now())
            ->where('is_published', 1)
            ->orderBy('published_at', 'desc')
            ->simplePaginate(config('blog.posts_per_page'));

        return [
            'title' => Settings::where('setting_name', 'blog_title')->find(1),
            'subtitle' => Settings::where('setting_name', 'blog_subtitle')->find(1),
            'posts' => $posts,
            'page_image' => config('blog.page_image'),
            'meta_description' => Settings::where('setting_name', 'blog_description')->find(1),
            'reverse_direction' => false,
            'tag' => null,
        ];
    }

protected function normalIndexData ( ) { $ posts = Post :: with ( 'tags' ) -> where ( 'published_at' , '<=' , Carbon :: now ( ) ) -> where ( 'is_published' , 1 ) -> orderBy ( 'published_at' , 'desc' ) -> simplePaginate ( config ( 'blog.posts_per_page' ) ) ; return [ 'title' => Settings :: where ( 'setting_name' , 'blog_title' ) -> find ( 1 ) , 'subtitle' => Settings :: where ( 'setting_name' , 'blog_subtitle' ) -> find ( 1 ) , 'posts' => $ posts , 'page_image' => config ( 'blog.page_image' ) , 'meta_description' => Settings :: where ( 'setting_name' , 'blog_description' ) -> find ( 1 ) , 'reverse_direction' => false , 'tag' => null , ] ; }

Return data for normal index page.

@return array


public function store(PostCreateRequest $request)
    {
        $post = Post::create($request->postFillData());
        $post->syncTags($request->get('tags', []));

        Session::put('_new-post', trans('canvas::messages.create_success', ['entity' => 'post']));

        return redirect()->route('canvas.admin.post.edit', $post->id);
    }

public function store ( PostCreateRequest $ request ) { $ post = Post :: create ( $ request -> postFillData ( ) ) ; $ post -> syncTags ( $ request -> get ( 'tags' , [ ] ) ) ; Session :: put ( '_new-post' , trans ( 'canvas::messages.create_success' , [ 'entity' => 'post' ] ) ) ; return redirect ( ) -> route ( 'canvas.admin.post.edit' , $ post -> id ) ; }

Store a newly created Post.

@param PostCreateRequest $request

@return \Illuminate\Http\RedirectResponse


public function update(PostUpdateRequest $request, $id)
    {
        $post = Post::findOrFail($id);
        $post->fill($request->postFillData());
        $post->save();
        $post->syncTags($request->get('tags', []));

        Session::put('_update-post', trans('canvas::messages.update_success', ['entity' => 'Post']));

        return redirect()->route('canvas.admin.post.edit', $id);
    }

public function update ( PostUpdateRequest $ request , $ id ) { $ post = Post :: findOrFail ( $ id ) ; $ post -> fill ( $ request -> postFillData ( ) ) ; $ post -> save ( ) ; $ post -> syncTags ( $ request -> get ( 'tags' , [ ] ) ) ; Session :: put ( '_update-post' , trans ( 'canvas::messages.update_success' , [ 'entity' => 'Post' ] ) ) ; return redirect ( ) -> route ( 'canvas.admin.post.edit' , $ id ) ; }

Update the Post.

@param PostUpdateRequest $request
@param int $id

@return \Illuminate\Http\RedirectResponse


protected function publishThemePublic(Theme $theme)
    {
        $target = public_path(self::TARGET_DIR);
        // Merge/overwrite theme public files.
        return $this->filesystem->copyDirectory($theme->getPublicDirectory(), $target);
    }

protected
function
publishThemePublic
(
Theme
$
theme
)
{
$
target
=
public_path
(
self
::
TARGET_DIR
)
;
// Merge/overwrite theme public files.
return
$
this
->
filesystem
->
copyDirectory
(
$
theme
->
getPublicDirectory
(
)
,
$
target
)
;
}

Publish a themes public assets. Themes MUST have public assets.
@param Theme $theme
@return bool

Publish a themes public assets . Themes MUST have public assets .


protected function publishThemeViews(Theme $theme, $clean = true)
    {
        $target = base_path('resources/views/'.self::TARGET_DIR);
        // Skip the ordeal if theme doesn't have views
        if (! $this->filesystem->exists($theme->getViewsDirectory())) {
            return true;
        }
        // Clean views directory.
        if ($clean) {
            $clean = $this->filesystem->deleteDirectory($target) || true;
        }
        // Publish theme views.
        $published = $this->filesystem->copyDirectory($theme->getViewsDirectory(), $target);

        return $published;
    }

Publish a themes views.
@param Theme $theme
@param bool $clean Views directory is cleaned to ensure no interference with none theme views.
@return bool


public function unTheme()
    {
        $publicTarget = public_path(self::TARGET_DIR);
        $publicSource = __DIR__.'/../../public';
        $viewsTarget = base_path('resources/views/'.self::TARGET_DIR);

        // Clean Views
        $clean = $this->filesystem->deleteDirectory($viewsTarget) || true;
        // Clean Public assets
        $clean = $clean && ($this->filesystem->cleanDirectory($publicTarget) || true);
        // Republish original/default public assets
        $unthemed = $clean && $this->filesystem->copyDirectory($publicSource, $publicTarget);

        // Actions to be taken after theme deactivation
        if ($unthemed) {
            // Update DB Setting
            Settings::updateOrCreate(['setting_name' => self::ACTIVE_KEY], ['setting_value' => 'default']);
        }

        return $unthemed;
    }

Deactivate all themes. Set canvas to "unthemed" state.
@return bool

Deactivate all themes . Set canvas to unthemed state .


public function getDefaultTheme()
    {
        $theme = new Theme('/', [
            'name'    => 'cnvs/canvas-theme-default',
            'extra'   => [
                'canvas-theme' => [
                    'title' => $this->getDefaultThemeName(),
                ],
            ],
        ]);
        $theme->setVersion(Constants::DEFAULT_THEME_VERSION);

        return $theme;
    }

public function getDefaultTheme ( ) { $ theme = new Theme ( '/' , [ 'name' => 'cnvs/canvas-theme-default' , 'extra' => [ 'canvas-theme' => [ 'title' => $ this -> getDefaultThemeName ( ) , ] , ] , ] ) ; $ theme -> setVersion ( Constants :: DEFAULT_THEME_VERSION ) ; return $ theme ; }


public function getActive()
    {
        return $active = Settings::getByName(self::ACTIVE_KEY) ?: ($this->config->get(self::ACTIVE_KEY) ?: 'default');
    }

public function getActive ( ) { return $ active = Settings :: getByName ( self :: ACTIVE_KEY ) ? : ( $ this -> config -> get ( self :: ACTIVE_KEY ) ? : 'default' ) ; }

The id's of the enabled extensions.

@return array


public static function getGeneralMiddleware()
    {
        $config = ConfigHelper::getWriter();
        $val = $config->get('route_middleware_general');

        return is_null($val) ? self::ROUTE_MIDDLEWARE_GROUPS_GENERAL : $val;
    }

public static function getGeneralMiddleware ( ) { $ config = ConfigHelper :: getWriter ( ) ; $ val = $ config -> get ( 'route_middleware_general' ) ; return is_null ( $ val ) ? self :: ROUTE_MIDDLEWARE_GROUPS_GENERAL : $ val ; }


public static function getInstalledMiddleware()
    {
        $config = ConfigHelper::getWriter();
        $val = $config->get('route_middleware_installed');

        return is_null($val) ? self::ROUTE_MIDDLEWARE_INSTALLED : $val;
    }

public static function getInstalledMiddleware ( ) { $ config = ConfigHelper :: getWriter ( ) ; $ val = $ config -> get ( 'route_middleware_installed' ) ; return is_null ( $ val ) ? self :: ROUTE_MIDDLEWARE_INSTALLED : $ val ; }


public static function getAdminMiddleware()
    {
        $config = ConfigHelper::getWriter();
        $val = $config->get('route_middleware_admin');

        return is_null($val) ? self::ROUTE_MIDDLEWARE_ADMIN : $val;
    }

public static function getAdminMiddleware ( ) { $ config = ConfigHelper :: getWriter ( ) ; $ val = $ config -> get ( 'route_middleware_admin' ) ; return is_null ( $ val ) ? self :: ROUTE_MIDDLEWARE_ADMIN : $ val ; }


public static function getBlogMain()
    {
        $config = ConfigHelper::getWriter();
        $val = $config->get('blog_path');

        return is_null($val) ? self::ROUTE_DEFAULT_BLOG_MAIN : $val;
    }

public static function getBlogMain ( ) { $ config = ConfigHelper :: getWriter ( ) ; $ val = $ config -> get ( 'blog_path' ) ; return is_null ( $ val ) ? self :: ROUTE_DEFAULT_BLOG_MAIN : $ val ; }


public static function getBlogPrefix()
    {
        $config = ConfigHelper::getWriter();
        $val = $config->get('blog_prefix');

        return is_null($val) ? self::ROUTE_DEFAULT_BLOG_PREFIX : $val;
    }

public static function getBlogPrefix ( ) { $ config = ConfigHelper :: getWriter ( ) ; $ val = $ config -> get ( 'blog_prefix' ) ; return is_null ( $ val ) ? self :: ROUTE_DEFAULT_BLOG_PREFIX : $ val ; }


public static function getAdminPrefix($withSlashes = false, $slashPos = 0)
    {
        $config = ConfigHelper::getWriter();
        $val = $config->get('admin_prefix');
        $prefix = is_null($val) ? self::ROUTE_DEFAULT_ADMIN_PREFIX : $val;

        // add slashes if requested
        if ($withSlashes && (! empty($prefix) && $prefix != '/')) {
            if ($slashPos == -1) {
                $prefix = "/{$prefix}";
            } elseif ($slashPos == 1) {
                $prefix = "{$prefix}/";
            } else {
                $prefix = "/{$prefix}/";
            }
        }

        // remove any duplicate slashes
        $prefix = str_replace('//', '/', $prefix);

        return $prefix;
    }

public
static
function
getAdminPrefix
(
$
withSlashes
=
false
,
$
slashPos
=
0
)
{
$
config
=
ConfigHelper
::
getWriter
(
)
;
$
val
=
$
config
->
get
(
'admin_prefix'
)
;
$
prefix
=
is_null
(
$
val
)
self
::
ROUTE_DEFAULT_ADMIN_PREFIX
:
$
val
;
// add slashes if requested
if
(
$
withSlashes
&&
(
!
empty
(
$
prefix
)
&&
$
prefix
!=
'/'
)
)
{
if
(
$
slashPos
==
1
)
{
$
prefix
=
"/{$prefix}"
;
}
elseif
(
$
slashPos
==
1
)
{
$
prefix
=
"{$prefix}/"
;
}
else
{
$
prefix
=
"/{$prefix}/"
;
}
}
// remove any duplicate slashes
$
prefix
=
str_replace
(
'//'
,
'/'
,
$
prefix
)
;
return
$
prefix
;
}

Get admin prefix.

@param bool $withSlashes Wheather wrapping slashes should be returned.
@param int $slashPos Used to determine where slashes must appear. (i.e. 1 => after, -1 => before, other => both sides)
@return string


public static function getAuthPrefix()
    {
        $config = ConfigHelper::getWriter();
        $val = $config->get('auth_prefix');

        return is_null($val) ? self::ROUTE_DEFAULT_AUTH_PREFIX : $val;
    }

public static function getAuthPrefix ( ) { $ config = ConfigHelper :: getWriter ( ) ; $ val = $ config -> get ( 'auth_prefix' ) ; return is_null ( $ val ) ? self :: ROUTE_DEFAULT_AUTH_PREFIX : $ val ; }


public static function getPasswordPrefix()
    {
        $config = ConfigHelper::getWriter();
        $val = $config->get('password_prefix');

        return is_null($val) ? self::ROUTE_DEFAULT_PASSWORD_PREFIX : $val;
    }

public static function getPasswordPrefix ( ) { $ config = ConfigHelper :: getWriter ( ) ; $ val = $ config -> get ( 'password_prefix' ) ; return is_null ( $ val ) ? self :: ROUTE_DEFAULT_PASSWORD_PREFIX : $ val ; }


public function index()
    {
        $params = request('search');

        $posts = Post::search($params)->get();
        $tags = Tag::search($params)->get();
        $users = User::search($params)->get();

        return view('canvas::backend.search.index', compact('posts', 'tags', 'users'));
    }

public function index ( ) { $ params = request ( 'search' ) ; $ posts = Post :: search ( $ params ) -> get ( ) ; $ tags = Tag :: search ( $ params ) -> get ( ) ; $ users = User :: search ( $ params ) -> get ( ) ; return view ( 'canvas::backend.search.index' , compact ( 'posts' , 'tags' , 'users' ) ) ; }

Display search result.

@return \Illuminate\View\View


public function getData()
    {
        $this->validate('amount', 'returnUrl');

        $data = new SimpleXMLElement('<GenerateRequest/>');
        $data->PxPayUserId = $this->getUsername();
        $data->PxPayKey = $this->getPassword();
        $data->TxnType = $this->action;
        $data->AmountInput = $this->getAmount();
        $data->CurrencyInput = $this->getCurrency();
        $data->UrlSuccess = $this->getReturnUrl();
        $data->UrlFail = $this->getCancelUrl() ?: $this->getReturnUrl();

        if ($this->getDescription()) {
            $data->MerchantReference = $this->getDescription();
        }

        if ($this->getTransactionId()) {
            $data->TxnId = $this->getTransactionId();
        }

        if ($this->getTransactionData1()) {
            $data->TxnData1 = $this->getTransactionData1();
        }

        if ($this->getTransactionData2()) {
            $data->TxnData2 = $this->getTransactionData2();
        }

        if ($this->getTransactionData3()) {
            $data->TxnData3 = $this->getTransactionData3();
        }

        if ($this->getCardReference()) {
            $data->DpsBillingId = $this->getCardReference();
        }

        return $data;
    }

public function getData ( ) { $ this -> validate ( 'amount' , 'returnUrl' ) ; $ data = new SimpleXMLElement ( '<GenerateRequest/>' ) ; $ data -> PxPayUserId = $ this -> getUsername ( ) ; $ data -> PxPayKey = $ this -> getPassword ( ) ; $ data -> TxnType = $ this -> action ; $ data -> AmountInput = $ this -> getAmount ( ) ; $ data -> CurrencyInput = $ this -> getCurrency ( ) ; $ data -> UrlSuccess = $ this -> getReturnUrl ( ) ; $ data -> UrlFail = $ this -> getCancelUrl ( ) ? : $ this -> getReturnUrl ( ) ; if ( $ this -> getDescription ( ) ) { $ data -> MerchantReference = $ this -> getDescription ( ) ; } if ( $ this -> getTransactionId ( ) ) { $ data -> TxnId = $ this -> getTransactionId ( ) ; } if ( $ this -> getTransactionData1 ( ) ) { $ data -> TxnData1 = $ this -> getTransactionData1 ( ) ; } if ( $ this -> getTransactionData2 ( ) ) { $ data -> TxnData2 = $ this -> getTransactionData2 ( ) ; } if ( $ this -> getTransactionData3 ( ) ) { $ data -> TxnData3 = $ this -> getTransactionData3 ( ) ; } if ( $ this -> getCardReference ( ) ) { $ data -> DpsBillingId = $ this -> getCardReference ( ) ; } return $ data ; }

Get the transaction data

@return SimpleXMLElement


public function scanFile($file)
    {
        $this->_sendCommand('SCAN ' . $file);

        $response = $this->_receiveResponse();

        return $this->_parseResponse($response);
    }

public
function
scanFile
(
$
file
)
{
$
this
->
_sendCommand
(
'SCAN '
.
$
file
)
;
$
response
=
$
this
->
_receiveResponse
(
)
;
return
$
this
->
_parseResponse
(
$
response
)
;
}

Scan a single file.

@param string $file The location of the file to scan.

@return array


public function multiscanFile($file)
    {
        $this->_sendCommand('MULTISCAN ' . $file);

        $response = $this->_receiveResponse();

        return $this->_parseResponse($response);
    }

public
function
multiscanFile
(
$
file
)
{
$
this
->
_sendCommand
(
'MULTISCAN '
.
$
file
)
;
$
response
=
$
this
->
_receiveResponse
(
)
;
return
$
this
->
_parseResponse
(
$
response
)
;
}

Scan a file or directory recursively using multiple threads.

@param string $file The location of the file or directory to scan.

@return array

Scan a file or directory recursively using multiple threads .


public function contScan($file)
    {
        $this->_sendCommand('CONTSCAN ' . $file);

        $response = $this->_receiveResponse();

        return $this->_parseResponse($response);
    }

public
function
contScan
(
$
file
)
{
$
this
->
_sendCommand
(
'CONTSCAN '
.
$
file
)
;
$
response
=
$
this
->
_receiveResponse
(
)
;
return
$
this
->
_parseResponse
(
$
response
)
;
}

Scan a file or directory recursively.

@param string $file The location of the file or directory to scan.

@return array


private function _receiveResponse($removeId = false, $readUntil = "\n")
    {
        $result = null;
        $readUntilLen = strlen($readUntil);
        do {
            if ($this->_socket->selectRead($this->_timeout)) {
                $rt = $this->_socket->read(4096, $this->_mode);
                if ($rt === "") {
                    break;
                }
                $result .= $rt;
                if (strcmp(substr($result, 0 - $readUntilLen), $readUntil) == 0) {
                    break;
                }
            } else if ($this->_mode === PHP_NORMAL_READ) {
                throw new ConnectionException("Timeout waiting to read response");
            } else {
                break;
            }
        } while (true);

        if (!$this->_inSession) {
            $this->_closeConnection();
        } else if ($removeId) {
            $result = preg_replace('/^\d+: /', "", $result, 1);
        }

        return trim($result);
    }

private
function
_receiveResponse
(
$
removeId
=
false
,
$
readUntil
=
"\n"
)
{
$
result
=
;
$
readUntilLen
=
strlen
(
$
readUntil
)
;
do
{
if
(
$
this
->
_socket
->
selectRead
(
$
this
->
_timeout
)
)
{
$
rt
=
$
this
->
_socket
->
read
(
4096
,
$
this
->
_mode
)
;
if
(
$
rt
===
""
)
{
break
;
}
$
result
.=
$
rt
;
if
(
strcmp
(
substr
(
$
result
,
0
$
readUntilLen
)
,
$
readUntil
)
==
0
)
{
break
;
}
}
else
if
(
$
this
->
_mode
===
PHP_NORMAL_READ
)
{
throw
new
ConnectionException
(
"Timeout waiting to read response"
)
;
}
else
{
break
;
}
}
while
(
true
)
;
if
(
!
$
this
->
_inSession
)
{
$
this
->
_closeConnection
(
)
;
}
else
if
(
$
removeId
)
{
$
result
=
preg_replace
(
'/^\d+: /'
,
""
,
$
result
,
1
)
;
}
return
trim
(
$
result
)
;
}

A wrapper to cleanly read a response from clamd.

@param bool $removeId
@param string $readUntil
@return string
@throws ConnectionException

A wrapper to cleanly read a response from clamd .


protected function processSingleFile(array $file)
    {
        // store it for future reference
        $file['original_name'] = $file['name'];

        // sanitize the file name
        $file['name'] = $this->sanitizeFileName($file['name']);

        $file = $this->validateFile($file);
        // if there are messages the file is not valid
        if (isset($file['messages']) && $file['messages']) {
            return $file;
        }

        // add the prefix
        $prefix = '';
        if (is_callable($this->prefix)) {
            $prefix = (string) call_user_func($this->prefix, $file['name']);
        } elseif (is_string($this->prefix)) {
            $prefix = (string) $this->prefix;
        }

        // if overwrite is not allowed, check if the file is already in the container
        if (!$this->overwrite) {
            if ($this->container->has($prefix . $file['name'])) {
                // add the timestamp to ensure the file is unique
                // method is not bulletproof but it's pretty safe
                $file['name'] = time() . '_' . $file['name'];
            }
        }

        // attempt to move the uploaded file into the container
        if (!$this->container->moveUploadedFile($file['tmp_name'], $prefix . $file['name'])) {
            $file['name'] = false;

            return $file;
        }

        $file['name'] = $prefix . $file['name'];
        // create the lock file if autoconfirm is disabled
        if (!$this->autoconfirm) {
            $this->container->save($file['name'] . '.lock', (string) time());
        }

        return $file;
    }

Processes a single uploaded file
- sanitize the name
- validates the file
- if valid, moves the file to the container

@param  array $file
@return array

Processes a single uploaded file - sanitize the name - validates the file - if valid moves the file to the container


protected function validateFile($file)
    {
        if (!$this->validator->validate($file)) {
            $file['messages'] = $this->validator->getMessages();
        }

        return $file;
    }

protected function validateFile ( $ file ) { if ( ! $ this -> validator -> validate ( $ file ) ) { $ file [ 'messages' ] = $ this -> validator -> getMessages ( ) ; } return $ file ; }

Validates a file according to the rules configured on the handler

@param $file
@return mixed


protected function sanitizeFileName($name)
    {
        if ($this->sanitizerCallback) {
            return call_user_func($this->sanitizerCallback, $name);
        }
        return preg_replace('/[^A-Za-z0-9\.]+/', '_', $name);
    }

protected function sanitizeFileName ( $ name ) { if ( $ this -> sanitizerCallback ) { return call_user_func ( $ this -> sanitizerCallback , $ name ) ; } return preg_replace ( '/[^A-Za-z0-9\.]+/' , '_' , $ name ) ; }

Sanitize the name of the uploaded file by stripping away bad characters
and replacing "invalid" characters with underscore _

@param  string $name
@return string

Sanitize the name of the uploaded file by stripping away bad characters and replacing invalid characters with underscore _


public function delete($file)
    {
        $file = $this->normalizePath($file);
        if (file_exists($this->baseDirectory . $file)) {
            return unlink($this->baseDirectory . $file);
        }

        return true;
    }

public function delete ( $ file ) { $ file = $ this -> normalizePath ( $ file ) ; if ( file_exists ( $ this -> baseDirectory . $ file ) ) { return unlink ( $ this -> baseDirectory . $ file ) ; } return true ; }

Delete the file from the container

@param  string $file
@return bool


public function moveUploadedFile($localFile, $destination)
    {
        $dir = dirname($this->baseDirectory . $destination);
        if (file_exists($localFile) && $this->ensureDirectory($dir)) {
            /**
             * we could use is_uploaded_file() and move_uploaded_file()
             * but in case of ajax uploads that would fail
             */
            if (is_readable($localFile)) {
                // rename() would be good but this is better because $localFile may become 'unwritable'
                $result = copy($localFile, $this->baseDirectory . $destination);
                @unlink($localFile);
                return $result;
            }
        }
        return false;
    }

Moves a temporary uploaded file to a destination in the container

@param  string $localFile   local path
@param  string $destination
@return bool


public function getList()
    {
        // read theme path
        $path = $this->app['config']->get('theme.path', base_path('resources/themes'));

        if (file_exists($path))
        {
            $dir_list = dir($path);
            while (false !== ($entry = $dir_list->read())) {
                if (file_exists($path . '/' . $entry . '/' . 'config.php'))
                    $list[] = $entry;
            }
        }

        return $list;

    }

public
function
getList
(
)
{
// read theme path
$
path
=
$
this
->
app
[
'config'
]
->
get
(
'theme.path'
,
base_path
(
'resources/themes'
)
)
;
if
(
file_exists
(
$
path
)
)
{
$
dir_list
=
dir
(
$
path
)
;
while
(
false
!==
(
$
entry
=
$
dir_list
->
read
(
)
)
)
{
if
(
file_exists
(
$
path
.
'/'
.
$
entry
.
'/'
.
'config.php'
)
)
$
list
[
]
=
$
entry
;
}
}
return
$
list
;
}

Returns the list of available themes names in an array.

@return array

Returns the list of available themes names in an array .


public function asset($path, $secure = null, $version = false)
    {

        if (!$this->theme) throw new ThemeException('Theme should be init first');

        $full_path = $this->_assetFullpath($path);

        $asset = $this->app['url']->asset($full_path, $secure);

        if ($version) {

            if (is_bool($version)) {
                $asset .= '?v=' . $this->_assetVersion($path);
            } else {
                $asset .= '?v=' . $version;
            }
        }

        return $asset;

    }

public
function
asset
(
$
path
,
$
secure
=
,
$
version
=
false
)
{
if
(
!
$
this
->
theme
)
throw
new
ThemeException
(
'Theme should be init first'
)
;
$
full_path
=
$
this
->
_assetFullpath
(
$
path
)
;
$
asset
=
$
this
->
app
[
'url'
]
->
asset
(
$
full_path
,
$
secure
)
;
if
(
$
version
)
{
if
(
is_bool
(
$
version
)
)
{
$
asset
.=
'?v='
.
$
this
->
_assetVersion
(
$
path
)
;
}
else
{
$
asset
.=
'?v='
.
$
version
;
}
}
return
$
asset
;
}

Generate an asset path for current theme.

@param $path
@param null $secure
@param bool $version
@throws Exceptions\ThemeException
@return mixed

Generate an asset path for current theme .


private function _assetVersion($path)
    {

        $full_path = $this->_assetFullpath($path);

        $file_path = public_path($full_path);

        if (file_exists($file_path)) {
            return filemtime($file_path);
        }

        return null;
    }

private function _assetVersion ( $ path ) { $ full_path = $ this -> _assetFullpath ( $ path ) ; $ file_path = public_path ( $ full_path ) ; if ( file_exists ( $ file_path ) ) { return filemtime ( $ file_path ) ; } return null ; }

Return filemtime of given asset or null if asset doesn't exists

@param $path
@return int|null

Return filemtime of given asset or null if asset doesn t exists


protected function getPath($path)
	{
		$rootPath = $this->config->get('theme::path', base_path('resources/themes'));

        return $rootPath.'/'.strtolower($this->getTheme()).'/' . $path;
	}

protected function getPath ( $ path ) { $ rootPath = $ this -> config -> get ( 'theme::path' , base_path ( 'resources/themes' ) ) ; return $ rootPath . '/' . strtolower ( $ this -> getTheme ( ) ) . '/' . $ path ; }

Get root writable path.

@param  string $path
@return string


protected function makeDir($path)
	{
		if ( ! $this->files->isDirectory($path))
		{
            $this->files->makeDirectory($path, 0777, true);
		}
	}

protected function makeDir ( $ path ) { if ( ! $ this -> files -> isDirectory ( $ path ) ) { $ this -> files -> makeDirectory ( $ path , 0777 , true ) ; } }

Make directory.

@param $path
@return void


protected function makeFile($file, $template = null, $assets = false)
	{
		if ( ! $this->files->exists($this->getPath($file)))
		{
			$content = $assets ? $this->getAssetsPath($file, true) : $this->getPath($file);

			$this->files->put($content, $template);
		}
	}

protected function makeFile ( $ file , $ template = null , $ assets = false ) { if ( ! $ this -> files -> exists ( $ this -> getPath ( $ file ) ) ) { $ content = $ assets ? $ this -> getAssetsPath ( $ file , true ) : $ this -> getPath ( $ file ) ; $ this -> files -> put ( $ content , $ template ) ; } }

Make file.

@param  string $file
@param  string $template
@param bool $assets
@return void


protected function getAssetsPath($path, $absolute = true)
	{
        $rootPath = $this->config->get('theme.assets_path', 'assets/themes');

        if ($absolute)
            $rootPath = public_path($rootPath);

		return $rootPath.'/'.strtolower($this->getTheme()).'/' . $path;
	}

protected function getAssetsPath ( $ path , $ absolute = true ) { $ rootPath = $ this -> config -> get ( 'theme.assets_path' , 'assets/themes' ) ; if ( $ absolute ) $ rootPath = public_path ( $ rootPath ) ; return $ rootPath . '/' . strtolower ( $ this -> getTheme ( ) ) . '/' . $ path ; }

Get assets writable path.

@param  string $path
@param bool $absolute
@return string


protected function getTemplate($template, $replacements = array())
    {

        $path = realpath(__DIR__ . '/../templates/' . $template . '.txt');

        $content = $this->files->get($path);

        if (!empty($replacements)) {
            $content = str_replace(array_keys($replacements), array_values($replacements), $content);
        }

        return $content;
    }

protected function getTemplate ( $ template , $ replacements = array ( ) ) { $ path = realpath ( __DIR__ . '/../templates/' . $ template . '.txt' ) ; $ content = $ this -> files -> get ( $ path ) ; if ( ! empty ( $ replacements ) ) { $ content = str_replace ( array_keys ( $ replacements ) , array_values ( $ replacements ) , $ content ) ; } return $ content ; }

Get default template.

@param  string $template
@param array $replacements
@return string


public function createAssetsAction(Request $request, $token)
    {
        if (!$request->isXmlHttpRequest()) {
            return $this->redirectToRoute('_profiler', ['token' => $token]);
        }

        $messages = $this->getSelectedMessages($request, $token);

        if ($messages instanceof Data) {
            $messages = $messages->getValue(true);
        }

        if (empty($messages)) {
            return new Response('No translations selected.');
        }

        $uploaded = array();
        $trans = $this->get('happyr.translation');
        foreach ($messages as $message) {
            if ($trans->createAsset($message)) {
                $uploaded[] = $message;
            }
        }

        $saved = count($uploaded);
        if ($saved > 0) {
            $this->get('happyr.translation.filesystem')->updateMessageCatalog($uploaded);
        }

        return new Response(sprintf('%s new assets created!', $saved));
    }

public
function
createAssetsAction
(
Request
$
request
,
$
token
)
{
if
(
!
$
request
->
isXmlHttpRequest
(
)
)
{
return
$
this
->
redirectToRoute
(
'_profiler'
,
[
'token'
=>
$
token
]
)
;
}
$
messages
=
$
this
->
getSelectedMessages
(
$
request
,
$
token
)
;
if
(
$
messages
instanceof
Data
)
{
$
messages
=
$
messages
->
getValue
(
true
)
;
}
if
(
empty
(
$
messages
)
)
{
return
new
Response
(
'No translations selected.'
)
;
}
$
uploaded
=
array
(
)
;
$
trans
=
$
this
->
get
(
'happyr.translation'
)
;
foreach
(
$
messages
as
$
message
)
{
if
(
$
trans
->
createAsset
(
$
message
)
)
{
$
uploaded
[
]
=
$
message
;
}
}
$
saved
=
count
(
$
uploaded
)
;
if
(
$
saved
>
0
)
{
$
this
->
get
(
'happyr.translation.filesystem'
)
->
updateMessageCatalog
(
$
uploaded
)
;
}
return
new
Response
(
sprintf
(
'%s new assets created!'
,
$
saved
)
)
;
}

Save the selected translation to resources.

@author Damien Alexandre (damienalexandre)

@param Request $request
@param string  $token

@Route("/{token}/translation/create-asset", name="_profiler_translations_create_assets")
@Method("POST")

@return Response

Save the selected translation to resources .


public function fetchTranslation(Message $message, $updateFs = false)
    {
        $project = $this->getProject($message);

        try {
            $resource = sprintf('translations/%s/%s', $message->getId(), $message->getLocale());
            $response = $this->makeApiRequest($project['api_key'], 'GET', $resource);
        } catch (HttpException $e) {
            if ($e->getCode() === 404) {
                //Message does not exist
                return;
            }
            throw $e;
        }

        $logoTranslation = $response['translation'];
        $messageTranslation = $message->getTranslation();
        $message->setTranslation($logoTranslation);

        // update filesystem
        if ($updateFs && $logoTranslation !== $messageTranslation) {
            $this->filesystemService->updateMessageCatalog([$message]);
        }

        return $logoTranslation;
    }

public
function
fetchTranslation
(
Message
$
message
,
$
updateFs
=
false
)
{
$
project
=
$
this
->
getProject
(
$
message
)
;
try
{
$
resource
=
sprintf
(
'translations/%s/%s'
,
$
message
->
getId
(
)
,
$
message
->
getLocale
(
)
)
;
$
response
=
$
this
->
makeApiRequest
(
$
project
[
'api_key'
]
,
'GET'
,
$
resource
)
;
}
catch
(
HttpException
$
e
)
{
if
(
$
e
->
getCode
(
)
===
404
)
{
//Message does not exist
return
;
}
throw
$
e
;
}
$
logoTranslation
=
$
response
[
'translation'
]
;
$
messageTranslation
=
$
message
->
getTranslation
(
)
;
$
message
->
setTranslation
(
$
logoTranslation
)
;
// update filesystem
if
(
$
updateFs
&&
$
logoTranslation
!==
$
messageTranslation
)
{
$
this
->
filesystemService
->
updateMessageCatalog
(
[
$
message
]
)
;
}
return
$
logoTranslation
;
}

Fetch a translation form Loco.

@param Message $message


public function updateTranslation(Message $message)
    {
        $project = $this->getProject($message);

        try {
            $resource = sprintf('translations/%s/%s', $message->getId(), $message->getLocale());
            $this->makeApiRequest($project['api_key'], 'POST', $resource, $message->getTranslation());
        } catch (HttpException $e) {
            if ($e->getCode() === 404) {
                //Asset does not exist
                if ($this->createAsset($message)) {
                    //Try again
                    return $this->updateTranslation($message);
                }

                return false;
            }
            throw $e;
        }

        $this->filesystemService->updateMessageCatalog([$message]);

        return true;
    }

public
function
updateTranslation
(
Message
$
message
)
{
$
project
=
$
this
->
getProject
(
$
message
)
;
try
{
$
resource
=
sprintf
(
'translations/%s/%s'
,
$
message
->
getId
(
)
,
$
message
->
getLocale
(
)
)
;
$
this
->
makeApiRequest
(
$
project
[
'api_key'
]
,
'POST'
,
$
resource
,
$
message
->
getTranslation
(
)
)
;
}
catch
(
HttpException
$
e
)
{
if
(
$
e
->
getCode
(
)
===
404
)
{
//Asset does not exist
if
(
$
this
->
createAsset
(
$
message
)
)
{
//Try again
return
$
this
->
updateTranslation
(
$
message
)
;
}
return
false
;
}
throw
$
e
;
}
$
this
->
filesystemService
->
updateMessageCatalog
(
[
$
message
]
)
;
return
true
;
}

Update the translation in Loco.

@param Message $message


public function flagTranslation(Message $message, $type = 0)
    {
        $project = $this->getProject($message);
        $flags = ['fuzzy', 'incorrect', 'provisional', 'unapproved', 'incomplete'];

        try {
            $resource = sprintf('translations/%s/%s/flag', $message->getId(), $message->getLocale());
            $this->makeApiRequest($project['api_key'], 'POST', $resource, ['flag' => $flags[$type]]);
        } catch (HttpException $e) {
            if ($e->getCode() === 404) {
                //Message does not exist
                return false;
            }
            throw $e;
        }

        return true;
    }

public
function
flagTranslation
(
Message
$
message
,
$
type
=
0
)
{
$
project
=
$
this
->
getProject
(
$
message
)
;
$
flags
=
[
'fuzzy'
,
'incorrect'
,
'provisional'
,
'unapproved'
,
'incomplete'
]
;
try
{
$
resource
=
sprintf
(
'translations/%s/%s/flag'
,
$
message
->
getId
(
)
,
$
message
->
getLocale
(
)
)
;
$
this
->
makeApiRequest
(
$
project
[
'api_key'
]
,
'POST'
,
$
resource
,
[
'flag'
=>
$
flags
[
$
type
]
]
)
;
}
catch
(
HttpException
$
e
)
{
if
(
$
e
->
getCode
(
)
===
404
)
{
//Message does not exist
return
false
;
}
throw
$
e
;
}
return
true
;
}

If there is something wrong with the translation, please flag it.

@param Message $message
@param int $type 0: Fuzzy, 1: Incorrect, 2: Provisional, 3: Unapproved, 4: Incomplete

@return bool

If there is something wrong with the translation please flag it .


public function createAsset(Message $message)
    {
        $project = $this->getProject($message);

        try {
            $response = $this->makeApiRequest($project['api_key'], 'POST', 'assets', [
                'id' => $message->getId(),
                'name' => $message->getId(),
                'type' => 'text',
                // Tell Loco not to translate the asset
                'default' => 'untranslated',
            ]);

            if ($message->hasParameters()) {
                // Send those parameter as a note to Loco
                $notes = '';
                foreach ($message->getParameters() as $key => $value) {
                    if (!is_array($value)) {
                        $notes .= 'Parameter: ' . $key . ' (i.e. : ' . $value . ")\n";
                    } else {
                        foreach ($value as $k => $v) {
                            $notes .= 'Parameter: ' . $k . ' (i.e. : ' . $v . ")\n";
                        }
                    }
                }

                $resource = sprintf('assets/%s.json', $message->getId());
                $this->makeApiRequest($project['api_key'], 'PATCH', $resource, ['notes' => $notes], 'json');
            }
        } catch (HttpException $e) {
            if ($e->getCode() === 409) {
                //conflict.. ignore
                return false;
            }
            throw $e;
        }

        // if this project has multiple domains. Make sure to tag it
        if (!empty($project['domains'])) {
            $this->addTagToAsset($project, $response['id'], $message->getDomain());
        }

        return true;
    }

Create a new asset in Loco.

@param Message $message

@return bool


public function downloadAllTranslations()
    {
        $data = [];
        foreach ($this->projects as $name => $config) {
            if (empty($config['domains'])) {
                $this->getUrls($data, $config, $name, false);
            } else {
                foreach ($config['domains'] as $domain) {
                    $this->getUrls($data, $config, $domain, true);
                }
            }
        }
        $this->requestManager->downloadFiles($this->filesystemService, $data);
    }

public function downloadAllTranslations ( ) { $ data = [ ] ; foreach ( $ this -> projects as $ name => $ config ) { if ( empty ( $ config [ 'domains' ] ) ) { $ this -> getUrls ( $ data , $ config , $ name , false ) ; } else { foreach ( $ config [ 'domains' ] as $ domain ) { $ this -> getUrls ( $ data , $ config , $ domain , true ) ; } } } $ this -> requestManager -> downloadFiles ( $ this -> filesystemService , $ data ) ; }

Download all the translations from Loco. This will replace all the local files.
This is a quick method of getting all the latest translations and assets.

Download all the translations from Loco . This will replace all the local files . This is a quick method of getting all the latest translations and assets .


public function uploadAllTranslations()
    {
        foreach ($this->projects as $name => $config) {
            if (empty($config['domains'])) {
                $this->doUploadDomains($config, $name, false);
            } else {
                foreach ($config['domains'] as $domain) {
                    $this->doUploadDomains($config, $domain, true);
                }
            }
        }
    }

public function uploadAllTranslations ( ) { foreach ( $ this -> projects as $ name => $ config ) { if ( empty ( $ config [ 'domains' ] ) ) { $ this -> doUploadDomains ( $ config , $ name , false ) ; } else { foreach ( $ config [ 'domains' ] as $ domain ) { $ this -> doUploadDomains ( $ config , $ domain , true ) ; } } } }

Upload all the translations from the symfony project into Loco. This will override
every changed strings in loco

Upload all the translations from the symfony project into Loco . This will override every changed strings in loco


public function synchronizeAllTranslations()
    {
        foreach ($this->projects as $name => $config) {
            if (empty($config['domains'])) {
                $this->doSynchronizeDomain($config, $name, false);
            } else {
                foreach ($config['domains'] as $domain) {
                    $this->doSynchronizeDomain($config, $domain, true);
                }
            }
        }
    }

public function synchronizeAllTranslations ( ) { foreach ( $ this -> projects as $ name => $ config ) { if ( empty ( $ config [ 'domains' ] ) ) { $ this -> doSynchronizeDomain ( $ config , $ name , false ) ; } else { foreach ( $ config [ 'domains' ] as $ domain ) { $ this -> doSynchronizeDomain ( $ config , $ domain , true ) ; } } } }

Synchronize all the translations with Loco. This will keep placeholders. This function is slower
than just to download the translations.

Synchronize all the translations with Loco . This will keep placeholders . This function is slower than just to download the translations .


public function onTerminate(Event $event)
    {
        if (empty($this->messages)) {
            return;
        }

        /** @var MessageCatalogue[] $catalogues */
        $catalogues = array();
        foreach ($this->messages as $m) {
            $key = $m->getLocale().$m->getDomain();
            if (!isset($catalogues[$key])) {
                $file = sprintf('%s/%s.%s.%s', $this->targetDir, $m->getDomain(), $m->getLocale(), $this->getFileExtension());

                try {
                    $catalogues[$key] = $this->loader->load($file, $m->getLocale(), $m->getDomain());
                } catch (NotFoundResourceException $e) {
                    $catalogues[$key] = new MessageCatalogue($m->getLocale());
                }
            }

            $translation = $m->getTranslation();
            if (empty($translation)) {
                if ($this->syncEmptyTranslations) {
                    $translation = sprintf('[%s]', $m->getId());
                } else {
                    continue;
                }
            }

            $catalogues[$key]->set($m->getId(), $translation, $m->getDomain());
        }

        foreach ($catalogues as $catalogue) {
            try {
                $this->dumper->dump($catalogue, ['path' => $this->targetDir]);
            } catch (\ErrorException $e) {
                // Could not save file
                // TODO better error handling
                throw $e;
            }
        }
    }

Update the file system after the Response has been sent back to the client.

@param Event $event

@throws \ErrorException
@throws \Exception

Update the file system after the Response has been sent back to the client .


private function copyValuesFromParentToProject($key, array &$config)
    {
        if (empty($config[$key])) {
            return;
        }

        foreach ($config['projects'] as &$project) {
            if (empty($project[$key])) {
                $project[$key] = $config[$key];
            }
        }
    }

private function copyValuesFromParentToProject ( $ key , array & $ config ) { if ( empty ( $ config [ $ key ] ) ) { return ; } foreach ( $ config [ 'projects' ] as & $ project ) { if ( empty ( $ project [ $ key ] ) ) { $ project [ $ key ] = $ config [ $ key ] ; } } }

Copy the parent configuration to the children.

@param string $key
@param array  $config

Copy the parent configuration to the children .


public function addHash($type, $hash)
    {
        $directive = self::DIRECTIVE_SCRIPT_SRC;
        if (!(isset($this->directives[$directive]) && is_array($this->directives[$directive]))) {
            $this->directives[$directive] = [];
        }

        if (!(isset($this->directives[$directive]['hashes']) && is_array($this->directives[$directive]['hashes']))) {
            $this->directives[$directive]['hashes'] = [];
        }

        $this->directives[$directive]['hashes'][$type][] = $hash;
    }

public function addHash ( $ type , $ hash ) { $ directive = self :: DIRECTIVE_SCRIPT_SRC ; if ( ! ( isset ( $ this -> directives [ $ directive ] ) && is_array ( $ this -> directives [ $ directive ] ) ) ) { $ this -> directives [ $ directive ] = [ ] ; } if ( ! ( isset ( $ this -> directives [ $ directive ] [ 'hashes' ] ) && is_array ( $ this -> directives [ $ directive ] [ 'hashes' ] ) ) ) { $ this -> directives [ $ directive ] [ 'hashes' ] = [ ] ; } $ this -> directives [ $ directive ] [ 'hashes' ] [ $ type ] [ ] = $ hash ; }

Add a hash value to the script-src.

@param string $type
@param string $hash
@throws InvalidDirectiveException


public function getValue()
    {
        $directives = [];
        foreach ($this->directives as $name => $value) {
            $directives[] = sprintf('%s %s', $name, $this->parseDirectiveValue($value));
        }

        if (!is_null($this->reflectedXssValue)) {
            $directives[] = sprintf('%s %s', 'reflected-xss', $this->reflectedXssValue);
        }

        if ($this->upgradeInsecureRequests) {
            $directives[] = $this->upgradeInsecureRequestsDirective;
        }

        if (!is_null($this->referrerValue)) {
            $directives[] = sprintf('%s %s', 'referrer', $this->referrerValue);
        }

        if (!is_null($this->reportUri)) {
            $directives[] = sprintf('%s %s', 'report-uri', $this->reportUri);
        }

        // No CSP policies set?
        if (count($directives) < 1) {
            return null;
        }

        return trim(sprintf('%s%s', implode($this->directiveSeparator, $directives), $this->directiveSeparator));
    }

public
function
getValue
(
)
{
$
directives
=
[
]
;
foreach
(
$
this
->
directives
as
$
name
=>
$
value
)
{
$
directives
[
]
=
sprintf
(
'%s %s'
,
$
name
,
$
this
->
parseDirectiveValue
(
$
value
)
)
;
}
if
(
!
is_null
(
$
this
->
reflectedXssValue
)
)
{
$
directives
[
]
=
sprintf
(
'%s %s'
,
'reflected-xss'
,
$
this
->
reflectedXssValue
)
;
}
if
(
$
this
->
upgradeInsecureRequests
)
{
$
directives
[
]
=
$
this
->
upgradeInsecureRequestsDirective
;
}
if
(
!
is_null
(
$
this
->
referrerValue
)
)
{
$
directives
[
]
=
sprintf
(
'%s %s'
,
'referrer'
,
$
this
->
referrerValue
)
;
}
if
(
!
is_null
(
$
this
->
reportUri
)
)
{
$
directives
[
]
=
sprintf
(
'%s %s'
,
'report-uri'
,
$
this
->
reportUri
)
;
}
// No CSP policies set?
if
(
count
(
$
directives
)
<
1
)
{
return
;
}
return
trim
(
sprintf
(
'%s%s'
,
implode
(
$
this
->
directiveSeparator
,
$
directives
)
,
$
this
->
directiveSeparator
)
)
;
}

Returns the value for the CSP header based on the loaded configuration.

@return string|null

Returns the value for the CSP header based on the loaded configuration .


protected function searchClassMap()
    {
        foreach ($this->composer->getClassMap() as $fqcn => $file)
        {
            if (Str::s($fqcn)->is($this->namespace.'*'))
            {
                $this->foundClasses[realpath($file)] = $fqcn;
            }
        }
    }

protected function searchClassMap ( ) { foreach ( $ this -> composer -> getClassMap ( ) as $ fqcn => $ file ) { if ( Str :: s ( $ fqcn ) -> is ( $ this -> namespace . '*' ) ) { $ this -> foundClasses [ realpath ( $ file ) ] = $ fqcn ; } } }

Searches the composer class map.

Results are added to the `$foundClasses` array.

@return void


protected function searchPsrMaps()
    {
        $prefixes = array_merge
        (
            $this->composer->getPrefixes(),
            $this->composer->getPrefixesPsr4()
        );

        $trimmedNs = Str::s($this->namespace)->trimRight('\\');

        $nsSegments = $trimmedNs->split('\\');

        foreach ($prefixes as $ns => $dirs)
        {
            $foundSegments = Str::s($ns)->trimRight('\\')
            ->longestCommonPrefix($trimmedNs)->split('\\');

            foreach ($foundSegments as $key => $segment)
            {
                if ((string) $nsSegments[$key] !== (string) $segment)
                {
                    continue 2;
                }
            }

            foreach ($dirs as $dir)
            {
                foreach ((new Finder)->in($dir)->files()->name('*.php') as $file)
                {
                    if ($file instanceof SplFileInfo)
                    {
                        $fqcn = (string)Str::s($file->getRelativePathname())
                        ->trimRight('.php')
                        ->replace('/', '\\')
                        ->ensureLeft($ns);

                        if (Str::s($fqcn)->is($this->namespace.'*'))
                        {
                            $this->foundClasses[$file->getRealPath()] = $fqcn;
                        }
                    }
                }
            }
        }
    }

protected function searchPsrMaps ( ) { $ prefixes = array_merge ( $ this -> composer -> getPrefixes ( ) , $ this -> composer -> getPrefixesPsr4 ( ) ) ; $ trimmedNs = Str :: s ( $ this -> namespace ) -> trimRight ( '\\' ) ; $ nsSegments = $ trimmedNs -> split ( '\\' ) ; foreach ( $ prefixes as $ ns => $ dirs ) { $ foundSegments = Str :: s ( $ ns ) -> trimRight ( '\\' ) -> longestCommonPrefix ( $ trimmedNs ) -> split ( '\\' ) ; foreach ( $ foundSegments as $ key => $ segment ) { if ( ( string ) $ nsSegments [ $ key ] !== ( string ) $ segment ) { continue 2 ; } } foreach ( $ dirs as $ dir ) { foreach ( ( new Finder ) -> in ( $ dir ) -> files ( ) -> name ( '*.php' ) as $ file ) { if ( $ file instanceof SplFileInfo ) { $ fqcn = ( string ) Str :: s ( $ file -> getRelativePathname ( ) ) -> trimRight ( '.php' ) -> replace ( '/' , '\\' ) -> ensureLeft ( $ ns ) ; if ( Str :: s ( $ fqcn ) -> is ( $ this -> namespace . '*' ) ) { $ this -> foundClasses [ $ file -> getRealPath ( ) ] = $ fqcn ; } } } } } }

Searches the composer PSR-x class maps.

Results are added to the `$foundClasses` array.

@return void

Searches the composer PSR - x class maps .


public function afterSave($project, $attributes)
    {
        // if "relation" is not present in the input, we simply detach all
        // related models by passing an empty array.
        $ids = isset($attributes['relation']) ? $attributes['relation'] : [];
        $project->manyToManyRelation()->sync($ids);
    }

Using afterSave, afterCreate or afterUpdate to set relationships is
often very useful. afterSave is called on both update and create.

Using afterSave afterCreate or afterUpdate to set relationships is often very useful . afterSave is called on both update and create .


protected function beforeQuery($query, $many)
    {
        // if this->active has been set to something, we add it to the query
        if ($this->active !== null) {
            $query->where('is_active', '=', $this->active);
        }

        // we want to always eager load members and comments.
        $query->with('members', 'comments');

        // let's say guests can only view projects with access level 1 or less.
        if (!$this->user) {
            $query->where('access_level', '<=', 1);
        }

        // unless user is an admin, we restrict every query to only show
        // projects with access_level lower than the logged in user's.
        else if (!$this->user->isAdmin()) {
            $query->where('access_level', '<=', $user->access_level);
        }
    }

This method is called before fetchMany and fetchSingle. We use it to add
functionality that should be present on every query.

Renamed from prepareQuery in 0.5

This method is called before fetchMany and fetchSingle . We use it to add functionality that should be present on every query .


protected function afterQuery($result)
    {
        // $result can be a single model, a paginator or a collection. We can
        // standardize the variable in this way to be able to use the same code
        // on all three types.
        if ($result instanceof \Illuminate\Database\Eloquent\Model) {
            // we might just do `return;` here if we didn't want our logic
            // applied to a single model.
            $projects = $result->newCollection([$result]);
        } else if ($result instanceof \Illuminate\Pagination\Paginator) {
            $projects = $result->getCollection();
        }

        // let's say we want to add some data onto the models after they've
        // been retrieved from the database. we want to add the count of a
        // relation, but don't want to mess with sub-selects and don't want to
        // waste memory by eager loading the relation, nor do we want to run
        // one query for each model.

        // build the query that gets the relationship count. some of this logic
        // could be moved into model scopes if you want. this is a rather
        // complex query so if you don't understand what is going on here,
        // don't worry too much. basically just getting the number of relations
        // attached to each project.
        $results = $this->model->relation()
            ->getRelated()->newQuery()
            ->whereIn('parent_id', $projects->lists('id'))
            ->selectRaw('parent_id, count(*) as relation_count')
            ->groupBy('parent_id')
            ->lists('relation_count', 'parent_id');

        // now add the attribute to each model.
        $projects->each(function($project) {
            $project->relation_count = $results[$project->id];
        });
    }

This method is called after fetchMany and fetchSingle. It is most useful
to append attributes onto more than one model for stuff that can't easily
be done via the query builder. Sometimes, for example, a subselect or
join or groupby can mess with the paginator.

Changed from prepareCollection/preparePaginator in 0.5

This method is called after fetchMany and fetchSingle . It is most useful to append attributes onto more than one model for stuff that can t easily be done via the query builder . Sometimes for example a subselect or join or groupby can mess with the paginator .


public function syncNewWastageItems(WastageModel $wastage, Collection $products, array $items)
    {
        $this->setWastage($wastage);

        $itemModels = [];

        foreach ($items as $key => $value) {
            $data = $this->buildItemData($key, $value, $products);
            $item = $this->create($data);

            $itemModels[] = $item;
        }

        return $itemModels;
    }

public function syncNewWastageItems ( WastageModel $ wastage , Collection $ products , array $ items ) { $ this -> setWastage ( $ wastage ) ; $ itemModels = [ ] ; foreach ( $ items as $ key => $ value ) { $ data = $ this -> buildItemData ( $ key , $ value , $ products ) ; $ item = $ this -> create ( $ data ) ; $ itemModels [ ] = $ item ; } return $ itemModels ; }

Sync item data for a new wastage.

@param  \REDACTED\Wastage\WastageModel            $wastage
@param  \Illuminate\Database\Eloquent\Collection  $products
@param  array                                     $items    Item input

@return array  Array of WastageItem models


public function syncExistingWastageItems(WastageModel $wastage, Collection $products, array $items)
    {
        $itemModels = [];

        foreach ($items as $key => $value) {
            if ($item = $this->findProductItem($wastage->items, $key)) {
                $this->checkIntegrity($item);
                $item->update($value);
            } else {
                $data = $this->buildItemData($key, $value, $products);
                $item = $this->create($data);
            }

            $itemModels[] = $item;
        }

        return $itemModels;
    }

public function syncExistingWastageItems ( WastageModel $ wastage , Collection $ products , array $ items ) { $ itemModels = [ ] ; foreach ( $ items as $ key => $ value ) { if ( $ item = $ this -> findProductItem ( $ wastage -> items , $ key ) ) { $ this -> checkIntegrity ( $ item ) ; $ item -> update ( $ value ) ; } else { $ data = $ this -> buildItemData ( $ key , $ value , $ products ) ; $ item = $ this -> create ( $ data ) ; } $ itemModels [ ] = $ item ; } return $ itemModels ; }

Sync items for an existing wastage. Updates the item entry if it exists,
or creates them if they don't.

@param  \REDACTED\Wastage\WastageModel            $wastage
@param  \Illuminate\Database\Eloquent\Collection  $products
@param  array                                     $items    Item input

@return array  Array of WastageItem models

Sync items for an existing wastage . Updates the item entry if it exists or creates them if they don t .


protected function findProductItem(Collection $items, $key)
    {
        if ($key instanceof ItemModel) {
            $key = $key->getKey();
        }

        return $items->first(function($id, $item) use($key) {
            return $item->product_id == $key;
        });
    }

protected function findProductItem ( Collection $ items , $ key ) { if ( $ key instanceof ItemModel ) { $ key = $ key -> getKey ( ) ; } return $ items -> first ( function ( $ id , $ item ) use ( $ key ) { return $ item -> product_id == $ key ; } ) ; }

Find the item entry of a specific product key in a collection of items.

@param  \Illuminate\Database\Eloquent\Collection $items
@param  mixed                                    $key   The product's primary key.

@return \REDACTED\Wastage\ItemModel|null

Find the item entry of a specific product key in a collection of items .


protected function checkIntegrity(ItemModel $item)
    {
        if ($item->department_id < 1) {
            $item->department()->associate($this->department);
        }

        if ($item->wastage_id < 1) {
            $item->wastage()->associate($this->wastage);
        }
    }

protected function checkIntegrity ( ItemModel $ item ) { if ( $ item -> department_id < 1 ) { $ item -> department ( ) -> associate ( $ this -> department ) ; } if ( $ item -> wastage_id < 1 ) { $ item -> wastage ( ) -> associate ( $ this -> wastage ) ; } }

Check the integrity of an item model. Add missing data if necessary.

@param  \REDACTED\Wastage\ItemModel $item

@return void

Check the integrity of an item model . Add missing data if necessary .


protected function buildItemData($key, array $data, Collection $products)
    {
        if (!$product = $products->find($key)) {
            throw new \RuntimeException("ID $key not found in products collection");
        }

        $this->setProduct($product);

        if (!empty($data['purchased_amount'])) {
            $data['purchased_for'] = $product->in_price;
        }

        if (!empty($data['sold_amount'])) {
            $data['sold_for'] = $product->out_price;
        }

        return $data;
    }

Build the pivot table data for a particular item.

@param  mixed                                    $key      The product's primary key.
@param  array                                    $data
@param  \Illuminate\Database\Eloquent\Collection $products

@return array

Build the pivot table data for a particular item .


protected function fillEntityAttributes($entity, array $attributes)
	{
		foreach ($attributes as $key => $value) {
			$entity->$key = $value;
		}
	}

protected function fillEntityAttributes ( $ entity , array $ attributes ) { foreach ( $ attributes as $ key => $ value ) { $ entity -> $ key = $ value ; } }

Fill an entity's attributes.

@param  mixed  $entity
@param  array  $attributes

@return void


protected function setupDefaultCriteria()
	{
		$defaultCriteria = $this->defaultCriteria;
		$this->defaultCriteria = [];

		foreach ($defaultCriteria as $criteria) {
			$this->addDefaultCriteria(new $criteria);
		}
	}

protected function setupDefaultCriteria ( ) { $ defaultCriteria = $ this -> defaultCriteria ; $ this -> defaultCriteria = [ ] ; foreach ( $ defaultCriteria as $ criteria ) { $ this -> addDefaultCriteria ( new $ criteria ) ; } }

Set up the repository's default criteria.

@return void

Set up the repository s default criteria .


protected function perform($action, $object, $attributes = array(), $validate = true)
	{
		$perform = 'perform' . ucfirst($action);
		if (!method_exists($this, $perform)) {
			throw new \BadMethodCallException("Method $perform does not exist on this class");
		}

		if ($validate === true) {
			if ($this->validateEntity) {
				if (!$this->valid($action, $this->getEntityAttributes($object))) return false;
			} else {
				if (!$this->valid($action, $attributes)) return false;
			}
		}

		$beforeResult = $this->doBefore($action, $object, $attributes);
		if ($beforeResult === false) return $beforeResult;

		$result = call_user_func_array([$this, $perform], [$object, $attributes]);
		if ($result === false) return $result;

		$this->doAfter($action, $result, $attributes);

		return $result;
	}

Perform an action.

Calls $this->before{$action} and $this->after{$action} before or after
$this->perform{action} has been called. Also calls $this->valid($action,
$attributes) for validation.

@param  string  $action
@param  mixed   $object
@param  mixed   $attributes
@param  boolean $validate

@return mixed


protected function doBeforeOrAfter($which, $action, array $args)
	{
		$method = $which.ucfirst($action);

		if (method_exists($this, $method)) {
			$result = call_user_func_array([$this, $method], $args);
			if ($result === false) return $result;
		}

		return null;
	}

protected function doBeforeOrAfter ( $ which , $ action , array $ args ) { $ method = $ which . ucfirst ( $ action ) ; if ( method_exists ( $ this , $ method ) ) { $ result = call_user_func_array ( [ $ this , $ method ] , $ args ) ; if ( $ result === false ) return $ result ; } return null ; }

Perform a before or after action.

@param  string $which  before or after
@param  string $action
@param  array  $args

@return false|null


public function valid($action, array $attributes)
	{
		if ($this->validator === null) {
			return true;
		}

		$result = $this->validator->valid($action, $attributes);

		if ($result === false) {
			$this->errors->merge($this->validator->getErrors());
		}

		return $result;
	}

public function valid ( $ action , array $ attributes ) { if ( $ this -> validator === null ) { return true ; } $ result = $ this -> validator -> valid ( $ action , $ attributes ) ; if ( $ result === false ) { $ this -> errors -> merge ( $ this -> validator -> getErrors ( ) ) ; } return $ result ; }

Validate a set of attributes against a certain action.

@param  string $action
@param  array  $attributes

@return boolean

Validate a set of attributes against a certain action .


protected function performQuery($query, $many)
	{
		$this->applyCriteria($query);

		if ($many === false) {
			$result = $this->getRegularQueryResults($query, false);

			if (!$result && $this->throwExceptions === true) {
				throw $this->getNotFoundException($query);
			}

			return $result;
		}

		return $this->paginate === false ?
			$this->getRegularQueryResults($query, true) :
			$this->getPaginatedQueryResults($query);
	}

protected function performQuery ( $ query , $ many ) { $ this -> applyCriteria ( $ query ) ; if ( $ many === false ) { $ result = $ this -> getRegularQueryResults ( $ query , false ) ; if ( ! $ result && $ this -> throwExceptions === true ) { throw $ this -> getNotFoundException ( $ query ) ; } return $ result ; } return $ this -> paginate === false ? $ this -> getRegularQueryResults ( $ query , true ) : $ this -> getPaginatedQueryResults ( $ query ) ; }

Perform a query.

@param  mixed   $query
@param  boolean $many

@return mixed


public function paginate($toggle)
	{
		$this->paginate = $toggle === false ? false : (int) $toggle;

		return $this;
	}

public function paginate ( $ toggle ) { $ this -> paginate = $ toggle === false ? false : ( int ) $ toggle ; return $ this ; }

Toggle pagination.

@param  false|int $toggle

@return $this


public function toggleExceptions($toggle, $toggleValidator = true)
	{
		$this->throwExceptions = (bool) $toggle;

		if ($this->validator && $toggleValidator) {
			$this->validator->toggleExceptions((bool) $toggle);
		}

		return $this;
	}

public function toggleExceptions ( $ toggle , $ toggleValidator = true ) { $ this -> throwExceptions = ( bool ) $ toggle ; if ( $ this -> validator && $ toggleValidator ) { $ this -> validator -> toggleExceptions ( ( bool ) $ toggle ) ; } return $ this ; }

Toggle throwing of exceptions.

@param  boolean $toggle
@param  boolean $toggleValidator Whether or not to toggle exceptions on
the validator as well as the repository. Defaults to true

@return $this


public function applyCriteria($query)
	{
		foreach ($this->defaultCriteria as $criteria) {
			$criteria->apply($query);
		}

		if (empty($this->criteria)) return;

		foreach ($this->criteria as $criteria) {
			$criteria->apply($query);
		}

		if ($this->resetCriteria) {
			$this->resetCriteria();
		}
	}

public function applyCriteria ( $ query ) { foreach ( $ this -> defaultCriteria as $ criteria ) { $ criteria -> apply ( $ query ) ; } if ( empty ( $ this -> criteria ) ) return ; foreach ( $ this -> criteria as $ criteria ) { $ criteria -> apply ( $ query ) ; } if ( $ this -> resetCriteria ) { $ this -> resetCriteria ( ) ; } }

Apply the repository's criteria onto a query builder.

@param  mixed $query

@return void

Apply the repository s criteria onto a query builder .


public function update($entity, array $attributes)
	{
		if ($this->validator) {
			$this->validator->replace('key', $this->getEntityKey($entity));
		}

		return $this->perform('update', $entity, $attributes, true) ? true : false;
	}

public function update ( $ entity , array $ attributes ) { if ( $ this -> validator ) { $ this -> validator -> replace ( 'key' , $ this -> getEntityKey ( $ entity ) ) ; } return $ this -> perform ( 'update' , $ entity , $ attributes , true ) ? true : false ; }

Update an entity with the given attributes and persist it.

@param  object  $entity
@param  array   $attributes

@return boolean

Update an entity with the given attributes and persist it .


protected function fetchList($query, $column = 'id', $key = null)
	{
		$this->doBefore('query', $query, true);
		$this->applyCriteria($query);

		return $query->lists($column, $key);
	}

protected function fetchList ( $ query , $ column = 'id' , $ key = null ) { $ this -> doBefore ( 'query' , $ query , true ) ; $ this -> applyCriteria ( $ query ) ; return $ query -> lists ( $ column , $ key ) ; }

Perform a query, fetching an array of columns.

@param  \Illuminate\Database\Query\Builder  $query
@param  string $column
@param  string $key    Column to be used as the array keys

@return array

Perform a query fetching an array of columns .


public function findByKey($key)
	{
		$query = $this->newQuery()
			->where($this->getKeyName(), '=', $key);

		return $this->fetchSingle($query);
	}

public function findByKey ( $ key ) { $ query = $ this -> newQuery ( ) -> where ( $ this -> getKeyName ( ) , '=' , $ key ) ; return $ this -> fetchSingle ( $ query ) ; }

Get a specific row by key in the repository.

@param  mixed $key

@return mixed

Get a specific row by key in the repository .


public function findByCriteria(CriteriaInterface $criteria)
	{
		$this->resetCriteria();
		$this->pushCriteria($criteria);

		return $this->fetchSingle($this->newQuery());
	}

public function findByCriteria ( CriteriaInterface $ criteria ) { $ this -> resetCriteria ( ) ; $ this -> pushCriteria ( $ criteria ) ; return $ this -> fetchSingle ( $ this -> newQuery ( ) ) ; }

Get a specific row by criteria.

@param  \anlutro\LaravelRepository\CriteriaInterface $criteria

@return mixed


public function getByCriteria(CriteriaInterface $criteria)
	{
		$this->resetCriteria();
		$this->pushCriteria($criteria);

		return $this->fetchMany($this->newQuery());
	}

public function getByCriteria ( CriteriaInterface $ criteria ) { $ this -> resetCriteria ( ) ; $ this -> pushCriteria ( $ criteria ) ; return $ this -> fetchMany ( $ this -> newQuery ( ) ) ; }

Get a collection of rows by a criteria. This resets all previously pushed
criteria.

@param  \anlutro\LaravelRepository\CriteriaInterface $criteria

@return mixed

Get a collection of rows by a criteria . This resets all previously pushed criteria .


public function getByKeys(array $keys)
	{
		if (count($keys) < 1) {
			throw new \InvalidArgumentException('Cannot getByKeys with an empty array');
		}

		$query = $this->newQuery()
			->whereIn($this->getKeyName(), $keys);

		return $this->fetchMany($query);
	}

public
function
getByKeys
(
array
$
keys
)
{
if
(
count
(
$
keys
)
<
1
)
{
throw
new
\
InvalidArgumentException
(
'Cannot getByKeys with an empty array'
)
;
}
$
query
=
$
this
->
newQuery
(
)
->
whereIn
(
$
this
->
getKeyName
(
)
,
$
keys
)
;
return
$
this
->
fetchMany
(
$
query
)
;
}

Get a collection of rows by an array of primary keys.

@param  array  $keys

@return mixed

@throws \InvalidArgumentException if $keys is empty

Get a collection of rows by an array of primary keys .


public function getList($column = 'id', $key = null)
	{
		return $this->fetchList($this->newQuery(), $column, $key);
	}

public function getList ( $ column = 'id' , $ key = null ) { return $ this -> fetchList ( $ this -> newQuery ( ) , $ column , $ key ) ; }

Get a list of columns from the repository.

@see    \Illuminate\Database\Query::lists()

@param  string $column
@param  string $key    Column to be used as the array keys

@return array

Get a list of columns from the repository .


protected function newAttributesQuery(array $attributes, $operator = '=')
	{
		$query = $this->newQuery();

		foreach ($attributes as $key => $value) {
			$query->where($key, $operator, $value);
		}

		return $query;
	}

protected function newAttributesQuery ( array $ attributes , $ operator = '=' ) { $ query = $ this -> newQuery ( ) ; foreach ( $ attributes as $ key => $ value ) { $ query -> where ( $ key , $ operator , $ value ) ; } return $ query ; }

Get a new query that searches by attributes.

@param  array  $attributes
@param  string $operator   Default: '='

@return mixed

Get a new query that searches by attributes .


private function replaceConfigValuePlaceholders($value)
    {
        if (is_array($value)) {
            foreach ($value as $subKey => $subValue) {
                $value[$subKey] = $this->replaceConfigValuePlaceholders($subValue);
            }
        } else {
            // replace environment variable
            if (preg_match(self::ENV_PARAMETER_PATTERN, $value, $matches)) {
                $envValue = getenv($matches[1]);
                if ($envValue === false) {
                    throw new \RuntimeException(sprintf(
                        'No environment variable found with name %s',
                        $matches[1]
                    ));
                }

                $value = $envValue;
            }
        }

        return $value;
    }

Convert placeholders in values of any config section

@param array|string $value

@return array|string


public function setViewPath($path)
    {
        $len = strlen($path) - 1;
        if ($path[$len] == '/') {
            $path = substr($path, 0, -1);
        }
        $realpath = realpath($path);;
        $this->_path = $realpath === false ? $path : $realpath;
    }

public function setViewPath ( $ path ) { $ len = strlen ( $ path ) - 1 ; if ( $ path [ $ len ] == '/' ) { $ path = substr ( $ path , 0 , - 1 ) ; } $ realpath = realpath ( $ path ) ; ; $ this -> _path = $ realpath === false ? $ path : $ realpath ; }

Sets the path where views are located.

@param string $path Path to the views directory.

@return void


public function send($file_path, $withDisposition=TRUE) {

        if (!is_readable($file_path)) {
            throw new \Exception('File not found or inaccessible!');
        }

        $size = filesize($file_path);
        if (!$this->disposition) {
            $this->disposition = $this->name($file_path);
        }

        if (!$this->type) {
            $this->type = $this->getContentType($file_path);
        }

        //turn off output buffering to decrease cpu usage
        $this->cleanAll();

        // required for IE, otherwise Content-Disposition may be ignored
        if (ini_get('zlib.output_compression')) {
            ini_set('zlib.output_compression', 'Off');
        }

        header('Content-Type: ' . $this->type);
        if ($withDisposition) {
            header('Content-Disposition: attachment; filename="' . $this->disposition . '"');
        }
        header('Accept-Ranges: bytes');

        // The three lines below basically make the
        // download non-cacheable
        header("Cache-control: private");
        header('Pragma: private');
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

        // multipart-download and download resuming support
        if (isset($_SERVER['HTTP_RANGE'])) {
            list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
            list($range) = explode(",", $range, 2);
            list($range, $range_end) = explode("-", $range);
            $range = intval($range);
            if (!$range_end) {
                $range_end = $size - 1;
            } else {
                $range_end = intval($range_end);
            }

            $new_length = $range_end - $range + 1;
            header("HTTP/1.1 206 Partial Content");
            header("Content-Length: $new_length");
            header("Content-Range: bytes $range-$range_end/$size");
        } else {
            $new_length = $size;
            header("Content-Length: " . $size);
        }

        /* output the file itself */
        $chunksize = $this->bytes; //you may want to change this
        $bytes_send = 0;

        $file = @fopen($file_path, 'rb');
        if ($file) {
            if (isset($_SERVER['HTTP_RANGE'])) {
                fseek($file, $range);
            }

            while (!feof($file) && (!connection_aborted()) && ($bytes_send < $new_length) ) {
                $buffer = fread($file, $chunksize);
                echo($buffer); //echo($buffer); // is also possible
                flush();
                usleep($this->sec * 1000000);
                $bytes_send += strlen($buffer);
            }
            fclose($file);
        } else {
            throw new \Exception('Error - can not open file.');
        }
    }

Sets-up headers and starts transfering bytes

@param string  $file_path
@param boolean $withDisposition
@throws Exception

Sets - up headers and starts transfering bytes


private function getContentType($path) {
        $result = false;
        if (is_file($path) === true) {
            if (function_exists('finfo_open') === true) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                if (is_resource($finfo) === true) {
                    $result = finfo_file($finfo, $path);
                }
                finfo_close($finfo);
            } else if (function_exists('mime_content_type') === true) {
                $result = preg_replace('~^(.+);.*$~', '$1', mime_content_type($path));
            } else if (function_exists('exif_imagetype') === true) {
                $result = image_type_to_mime_type(exif_imagetype($path));
            }
        }
        return $result;
    }

private function getContentType ( $ path ) { $ result = false ; if ( is_file ( $ path ) === true ) { if ( function_exists ( 'finfo_open' ) === true ) { $ finfo = finfo_open ( FILEINFO_MIME_TYPE ) ; if ( is_resource ( $ finfo ) === true ) { $ result = finfo_file ( $ finfo , $ path ) ; } finfo_close ( $ finfo ) ; } else if ( function_exists ( 'mime_content_type' ) === true ) { $ result = preg_replace ( '~^(.+);.*$~' , '$1' , mime_content_type ( $ path ) ) ; } else if ( function_exists ( 'exif_imagetype' ) === true ) { $ result = image_type_to_mime_type ( exif_imagetype ( $ path ) ) ; } } return $ result ; }

method for getting mime type of a file
@param string $path
@return string $mime_type


public function map(Action $action)
    {
        $exception = $action->getArguments();
        $exception = $exception['exception'];

        $this->_logger->debug('Exception mapper invoked with: ' . $action->getId());

        // Lookup a controller that can handle this url.
        foreach ($this->_map as $map) {
            $controllerException = $map[0];
            $controller = $map[1];
            if (!($exception instanceof $controllerException)) {
                continue;
            }
            return new DispatchInfo(
                $action, $controller,
                str_replace('\\', '_', $controllerException) . 'Exception'
            );
        }
        return false;
    }

This will map an exception action to a controller. Will look for
an instance of the mapped exception to the thrown exception.

@param Action $action Original action (exception).

@return array [0] => Controller [1] => Method to call (With
'Exception' appended to the end of the method name).

This will map an exception action to a controller . Will look for an instance of the mapped exception to the thrown exception .


public function setAspect(AspectDefinition $aspect)
    {
        $name = $aspect->getName();
        $this->_aspects[$name] = $aspect;
        $this->_cache->store('AspectManagerAspect' . $name, $aspect);
        $this->_cache->store('Aspects', $this->_aspects);
    }

public function setAspect ( AspectDefinition $ aspect ) { $ name = $ aspect -> getName ( ) ; $ this -> _aspects [ $ name ] = $ aspect ; $ this -> _cache -> store ( 'AspectManagerAspect' . $ name , $ aspect ) ; $ this -> _cache -> store ( 'Aspects' , $ this -> _aspects ) ; }

Adds or overwrites the given aspect.

@param AspectDefinition $aspect Aspect.

@return void


public function setPointcut(PointcutDefinition $pointcut)
    {
        $name = $pointcut->getName();
        $this->_pointcuts[$name] = $pointcut;
        $this->_cache->store('AspectManagerPointcut' . $name, $pointcut);
    }

public function setPointcut ( PointcutDefinition $ pointcut ) { $ name = $ pointcut -> getName ( ) ; $ this -> _pointcuts [ $ name ] = $ pointcut ; $ this -> _cache -> store ( 'AspectManagerPointcut' . $ name , $ pointcut ) ; }

Adds or overwrites the given pointcut.

@param PointcutDefinition $pointcut Pointcut.

@return void


public function getPointcut($pointcut)
    {
        if (isset($this->_pointcuts[$pointcut])) {
            return $this->_pointcuts[$pointcut];
        } else {
            $result = false;
            $value = $this->_cache->fetch('AspectManagerPointcut' . $pointcut, $result);
            if ($result === true) {
                $this->_pointcuts[$pointcut] = $value;
                return $value;
            } else {
                foreach ($this->_pointcutProviders as $provider) {
                    $value = $provider->getPointcut($pointcut);
                    if ($value !== false) {
                        $this->setPointcut($value);
                        return $value;
                    }
                }
            }
        }
        return false;
    }

public function getPointcut ( $ pointcut ) { if ( isset ( $ this -> _pointcuts [ $ pointcut ] ) ) { return $ this -> _pointcuts [ $ pointcut ] ; } else { $ result = false ; $ value = $ this -> _cache -> fetch ( 'AspectManagerPointcut' . $ pointcut , $ result ) ; if ( $ result === true ) { $ this -> _pointcuts [ $ pointcut ] = $ value ; return $ value ; } else { foreach ( $ this -> _pointcutProviders as $ provider ) { $ value = $ provider -> getPointcut ( $ pointcut ) ; if ( $ value !== false ) { $ this -> setPointcut ( $ value ) ; return $ value ; } } } } return false ; }

Returns a PointcutDefinition or false if none found.

@param string $pointcut Pointcut id or name.

@return PointcutDefinition

Returns a PointcutDefinition or false if none found .


private function _getCandidateFilesForClassScanning($path)
    {
        $cacheKey = "$path.candidatefiles";
        $result = false;
        $files = $this->_cache->fetch($cacheKey, $result);
        if ($result === true) {
            return $files;
        }
        $files = array();
        if (is_dir($path)) {
            foreach (scandir($path) as $entry) {
                if ($entry == '.' || $entry == '..') {
                    continue;
                }
                $entry = "$path/$entry";
                foreach ($this->_getCandidateFilesForClassScanning($entry) as $file) {
                    $files[] = $file;
                }
            }
        } else if ($this->_isScannable($path)) {
            $files[] = realpath($path);
        }
        $this->_cache->store($cacheKey, $files);
        return $files;
    }

private function _getCandidateFilesForClassScanning ( $ path ) { $ cacheKey = "$path.candidatefiles" ; $ result = false ; $ files = $ this -> _cache -> fetch ( $ cacheKey , $ result ) ; if ( $ result === true ) { return $ files ; } $ files = array ( ) ; if ( is_dir ( $ path ) ) { foreach ( scandir ( $ path ) as $ entry ) { if ( $ entry == '.' || $ entry == '..' ) { continue ; } $ entry = "$path/$entry" ; foreach ( $ this -> _getCandidateFilesForClassScanning ( $ entry ) as $ file ) { $ files [ ] = $ file ; } } } else if ( $ this -> _isScannable ( $ path ) ) { $ files [ ] = realpath ( $ path ) ; } $ this -> _cache -> store ( $ cacheKey , $ files ) ; return $ files ; }

Returns all files elegible for scanning for classes.

@param string $path Absolute path to a directory or filename.

@return string[]

Returns all files elegible for scanning for classes .


private function _isScannable($path)
    {
        $extensionPos = strrpos($path, '.');
        if ($extensionPos === false) {
            return false;
        }
        if (substr($path, $extensionPos, 4) != '.php') {
            return false;
        }
        return true;
    }

private function _isScannable ( $ path ) { $ extensionPos = strrpos ( $ path , '.' ) ; if ( $ extensionPos === false ) { return false ; } if ( substr ( $ path , $ extensionPos , 4 ) != '.php' ) { return false ; } return true ; }

Returns true if the given filesystem entry is interesting to scan.

@param string $path Filesystem entry.

Returns true if the given filesystem entry is interesting to scan .


public static function typeToString($type)
    {
        switch($type)
        {
        case E_USER_ERROR:
            return 'User Error';
        case E_USER_WARNING:
            return 'User Warning';
        case E_USER_NOTICE:
            return 'User Notice';
        case E_USER_DEPRECATED:
            return 'User deprecated';
        case E_DEPRECATED:
            return 'Deprecated';
        case E_RECOVERABLE_ERROR:
            return 'Recoverable error';
        case E_STRICT:
            return 'Strict';
        case E_WARNING:
            return 'Warning';
        case E_NOTICE:
            return 'Notice';
        case E_ERROR:
            return 'Error';
        default:
            return 'Unknown';
        }
    }

public
static
function
typeToString
(
$
type
)
{
switch
(
$
type
)
{
case
E_USER_ERROR
:
return
'User Error'
;
case
E_USER_WARNING
:
return
'User Warning'
;
case
E_USER_NOTICE
:
return
'User Notice'
;
case
E_USER_DEPRECATED
:
return
'User deprecated'
;
case
E_DEPRECATED
:
return
'Deprecated'
;
case
E_RECOVERABLE_ERROR
:
return
'Recoverable error'
;
case
E_STRICT
:
return
'Strict'
;
case
E_WARNING
:
return
'Warning'
;
case
E_NOTICE
:
return
'Notice'
;
case
E_ERROR
:
return
'Error'
;
default
:
return
'Unknown'
;
}
}

Returns a human readable string description of the given error type.

@param integer $type Error type to convert to string, from getType()

@return string

Returns a human readable string description of the given error type .


public function dispatch(DispatchInfo $dispatchInfo)
    {
        $controller = $dispatchInfo->handler;
        $actionHandler = $dispatchInfo->method;
        $action = $dispatchInfo->action;
        if (!method_exists($controller, $actionHandler)) {
            throw new MvcException('No valid action handler found: ' . $actionHandler);
        }
        $interceptors = $dispatchInfo->interceptors;
        $filtersPassed = true;
        $result = false;
        foreach ($interceptors as $interceptor) {
            $this->_logger->debug("Running pre filter: " . get_class($interceptor));
            $result = $interceptor->preHandle($action, $controller);
            if ($result === false) {
                $filtersPassed = false;
                $this->_logger->debug("Filter returned false, stopping dispatch");
                break;
            } else if ($result instanceof ModelAndView) {
                return $result;
            }
        }
        if ($filtersPassed) {
            $result = $this->invokeAction($controller, $actionHandler, $action->getArguments());
            foreach ($interceptors as $interceptor) {
                $this->_logger->debug("Running post filter: " . get_class($interceptor));
                $interceptor->postHandle($action, $controller);
            }
        }
        return $result;
    }

Main action. Will use the action mapper to get a controller that can
handle the given Action, and then the viewresolver to get a View that
can render the returned ModelAndView from the controller.

@param Action  $action Action to dispatch.

@throws MvcException
@return void

Main action . Will use the action mapper to get a controller that can handle the given Action and then the viewresolver to get a View that can render the returned ModelAndView from the controller .


private function invokeAction($object, $method, array $arguments)
    {
        $methodInfo = $this->reflectionFactory->getMethod(
            get_class($object), $method
        );
        $parameters = $methodInfo->getParameters();
        $values = array();
        $total = count($parameters);
        for ($i = 0; $i < $total; $i++) {
            $parameter = array_shift($parameters);
            $name = $parameter->getName();
            if (isset($arguments[$name])) {
                $values[] = $arguments[$name];
            } else if ($parameter->isOptional()) {
                $values[] = $parameter->getDefaultValue();
            } else {
                $ctl = get_class($object);
                throw new MvcException(
                	"Missing required argument: $name for action $ctl:$method"
                );
            }
        }
        return $methodInfo->invokeArgs($object, $values);
    }

Calls the specified method from the specifed object using the specified
arguments map.

@param object $object
@param string $method Method name
@param array $arguments Map of arguments, where key is argument name,
and value is argument value.

@return mxied

Calls the specified method from the specifed object using the specified arguments map .


public function hasActivity()
    {
        if (!$this->isConnected()) {
            return false;
        }
        $read = array($this->socket);
        $write = null;
        $ex = null;
        $result = socket_select($read, $write, $ex, 0, 0);
        if ($result === false) {
            throw new TcpException(
            	'Error selecting from socket: '
                . socket_strerror(socket_last_error($this->socket))
            );
        }
        return !empty($read);
    }

public
function
hasActivity
(
)
{
if
(
!
$
this
->
isConnected
(
)
)
{
return
false
;
}
$
read
=
array
(
$
this
->
socket
)
;
$
write
=
;
$
ex
=
;
$
result
=
socket_select
(
$
read
,
$
write
,
$
ex
,
0
,
0
)
;
if
(
$
result
===
false
)
{
throw
new
TcpException
(
'Error selecting from socket: '
.
socket_strerror
(
socket_last_error
(
$
this
->
socket
)
)
)
;
}
return
!
empty
(
$
read
)
;
}

Call this one to see if this peer has any activity in the socket.

@return boolean

Call this one to see if this peer has any activity in the socket .