<commit_before><?php namespace App\Repositories;

use App\Models\Tag as Tag;
use App\Models\ConfessionLog as ConfessionLog;
use App\Repositories\BaseRepository;

class ConfessionsRepository extends BaseRepository {

    private $_pageToken = '';

    public function model()
    {
        return 'App\Models\Confession';
    }

    public function create(array $data, $categories = [])
    {
        $confession = $this->model->create($data);
        $confession->status_updated_at = new \DateTime();

        $this->syncTags($confession);
        $this->syncCategories($confession, $categories);

        return $confession->save();
    }

    public function update($id, array $data, $categories = [])
    {
        $confession = $this->model->find($id);
        if (!$confession) {
            throw new \Exception("Model #{$id} is not found");
        }

        // Switch status
        $switched = false;
        if ($data['status'] != $confession->status) {
            $this->switchStatus($confession, $data['status'], false);
            $switched = true;
        }

        $confession->fill($data);

        // Update Facebook if it's featured or approved
        if (!$switched && ($confession->status == 'Featured' || $confession->status == 'Approved'))
            $this->postToFacebook($confession);

        $this->syncTags($confession);
        $this->syncCategories($confession, $categories);

        return $confession->save();
    }

    public function delete($id)
    {
        $confession = $this->model->find($id);
        if (!$confession) {
            throw new \Exception("Model #{$id} is not found");
        }

        try {
            if ($confession->fb_post_id) {
                $this->deleteFromFacebook($confession);
            }
        } catch (\Exception $e) {
            $confession->delete();
        }

        return $confession->delete();
    }

    public function switchStatus($confession, $new, $save = true)
    {
        switch ($new) {
            case 'Featured':
            case 'Approved':
                if (!$confession->fb_post_id) {
                    $confession->fb_post_id = $this->postToFacebook($confession);
                }
                break;
            case 'Pending':
            case 'Rejected':
                if ($confession->fb_post_id) {
                    $this->deleteFromFacebook($confession);
                }
                break;
        }
        $old = $confession->status;
        $confession->status = $new;
        $confession->status_updated_at = new \DateTime();

        if (\Auth::check()) {
            $user = \Auth::user()->getAuthIdentifier();
            $log = new ConfessionLog([
                'status_before' => $old,
                'status_after' => $new,
                'changed_by_user' => $user,
                'created_on' => new \DateTime(),
            ]);
            $confession->logs()->save($log);
        }

        if ($save)
            return $confession->save();
        else
            return true;
    }

    public function getPageToken()
    {
        if (!$this->_pageToken) {
            $profile = \Auth::user()->profiles()->where('provider_name', '=', 'facebook')->get();
            if (count($profile) !== 1) {
                return false;
            }
            $this->_pageToken = $profile[0]->page_token;
        }
        return $this->_pageToken;
    }

    protected function postToFacebook($confession)
    {
        if ($confession->images) {
            if ($confession->fb_post_id) {
                $endpoint = '/' . $confession->fb_post_id;
            } else {
                $endpoint = '/' . env('FACEBOOK_PAGE_ID', '') . '/photos';
            }

            $response = \Facebook::post($endpoint, [
                'message' => $confession->content . "\n-\n #" . $confession->confession_id . ": " . url('/confession/' . $confession->confession_id),
                'url'  => $confession->images,
            ], $this->getPageToken())->getGraphObject();

            if ($confession->fb_post_id) {
                return $confession->fb_post_id;
            } else {
                return $response['id'];
            }
        } else {
            if ($confession->fb_post_id) {
                $endpoint = '/' . env('FACEBOOK_PAGE_ID', '') . '_' . $confession->fb_post_id;
            } else {
                $endpoint = '/' . env('FACEBOOK_PAGE_ID', '') . '/feed';
            }

            $response = \Facebook::post($endpoint, [
                'message' => $confession->content . "\n-\n #" . $confession->confession_id . ": " . url('/confession/' . $confession->confession_id),
                // 'link' => url('/#!/confession/' . $confession->confession_id)
            ], $this->getPageToken())->getGraphObject();

            if ($confession->fb_post_id) {
                return $confession->fb_post_id;
            } else {
                return explode('_', $response['id'])[1];
            }
        }
    }

    protected function deleteFromFacebook($confession)
    {
        try {
            if ($confession->images) {
                \Facebook::delete('/' . $confession->fb_post_id, [], $this->getPageToken());
            } else {
                \Facebook::delete('/' . env('FACEBOOK_PAGE_ID', '') . '_' . $confession->fb_post_id, [], $this->getPageToken());
            }
        } catch (\Exception $e) {
        }
        $confession->fb_post_id = '';
    }

    protected function syncTags(&$confession)
    {
        $tagNames = $this->getTagNamesFromContent($confession->content);
        $tagsToSync = [];
        foreach ($tagNames as $tagName) {
            $tag = Tag::firstOrCreate(['confession_tag' => $tagName]);
            $tagsToSync[] = $tag->confession_tag_id;
        }
        $confession->tags()->sync($tagsToSync);

        return $confession;
    }

    protected function syncCategories(&$confession, $categories)
    {
        $confession->categories()->sync($categories);
        return $confession;
    }

    protected function getTagNamesFromContent($content)
    {
        preg_match_all('/(#\w+)/', $content, $matches);
        return array_unique(array_shift($matches));
    }

}<commit_msg>Fixed bug where editing confessions with no categories ended up with a PHP error.<commit_after><?php namespace App\Repositories;

use App\Models\Tag as Tag;
use App\Models\ConfessionLog as ConfessionLog;
use App\Repositories\BaseRepository;

class ConfessionsRepository extends BaseRepository {

    private $_pageToken = '';

    public function model()
    {
        return 'App\Models\Confession';
    }

    public function create(array $data, $categories = [])
    {
        $confession = $this->model->create($data);
        $confession->status_updated_at = new \DateTime();

        $this->syncTags($confession);
        $this->syncCategories($confession, $categories);

        return $confession->save();
    }

    public function update($id, array $data, $categories = [])
    {
        $confession = $this->model->find($id);
        if (!$confession) {
            throw new \Exception("Model #{$id} is not found");
        }

        // Switch status
        $switched = false;
        if ($data['status'] != $confession->status) {
            $this->switchStatus($confession, $data['status'], false);
            $switched = true;
        }

        $confession->fill($data);

        // Update Facebook if it's featured or approved
        if (!$switched && ($confession->status == 'Featured' || $confession->status == 'Approved'))
            $this->postToFacebook($confession);

        $this->syncTags($confession);
        $this->syncCategories($confession, $categories);

        return $confession->save();
    }

    public function delete($id)
    {
        $confession = $this->model->find($id);
        if (!$confession) {
            throw new \Exception("Model #{$id} is not found");
        }

        try {
            if ($confession->fb_post_id) {
                $this->deleteFromFacebook($confession);
            }
        } catch (\Exception $e) {
            $confession->delete();
        }

        return $confession->delete();
    }

    public function switchStatus($confession, $new, $save = true)
    {
        switch ($new) {
            case 'Featured':
            case 'Approved':
                if (!$confession->fb_post_id) {
                    $confession->fb_post_id = $this->postToFacebook($confession);
                }
                break;
            case 'Pending':
            case 'Rejected':
                if ($confession->fb_post_id) {
                    $this->deleteFromFacebook($confession);
                }
                break;
        }
        $old = $confession->status;
        $confession->status = $new;
        $confession->status_updated_at = new \DateTime();

        if (\Auth::check()) {
            $user = \Auth::user()->getAuthIdentifier();
            $log = new ConfessionLog([
                'status_before' => $old,
                'status_after' => $new,
                'changed_by_user' => $user,
                'created_on' => new \DateTime(),
            ]);
            $confession->logs()->save($log);
        }

        if ($save)
            return $confession->save();
        else
            return true;
    }

    public function getPageToken()
    {
        if (!$this->_pageToken) {
            $profile = \Auth::user()->profiles()->where('provider_name', '=', 'facebook')->get();
            if (count($profile) !== 1) {
                return false;
            }
            $this->_pageToken = $profile[0]->page_token;
        }
        return $this->_pageToken;
    }

    protected function postToFacebook($confession)
    {
        if ($confession->images) {
            if ($confession->fb_post_id) {
                $endpoint = '/' . $confession->fb_post_id;
            } else {
                $endpoint = '/' . env('FACEBOOK_PAGE_ID', '') . '/photos';
            }

            $response = \Facebook::post($endpoint, [
                'message' => $confession->content . "\n-\n #" . $confession->confession_id . ": " . url('/confession/' . $confession->confession_id),
                'url'  => $confession->images,
            ], $this->getPageToken())->getGraphObject();

            if ($confession->fb_post_id) {
                return $confession->fb_post_id;
            } else {
                return $response['id'];
            }
        } else {
            if ($confession->fb_post_id) {
                $endpoint = '/' . env('FACEBOOK_PAGE_ID', '') . '_' . $confession->fb_post_id;
            } else {
                $endpoint = '/' . env('FACEBOOK_PAGE_ID', '') . '/feed';
            }

            $response = \Facebook::post($endpoint, [
                'message' => $confession->content . "\n-\n #" . $confession->confession_id . ": " . url('/confession/' . $confession->confession_id),
                // 'link' => url('/#!/confession/' . $confession->confession_id)
            ], $this->getPageToken())->getGraphObject();

            if ($confession->fb_post_id) {
                return $confession->fb_post_id;
            } else {
                return explode('_', $response['id'])[1];
            }
        }
    }

    protected function deleteFromFacebook($confession)
    {
        try {
            if ($confession->images) {
                \Facebook::delete('/' . $confession->fb_post_id, [], $this->getPageToken());
            } else {
                \Facebook::delete('/' . env('FACEBOOK_PAGE_ID', '') . '_' . $confession->fb_post_id, [], $this->getPageToken());
            }
        } catch (\Exception $e) {
        }
        $confession->fb_post_id = '';
    }

    protected function syncTags(&$confession)
    {
        $tagNames = $this->getTagNamesFromContent($confession->content);
        $tagsToSync = [];
        foreach ($tagNames as $tagName) {
            $tag = Tag::firstOrCreate(['confession_tag' => $tagName]);
            $tagsToSync[] = $tag->confession_tag_id;
        }
        $confession->tags()->sync($tagsToSync);

        return $confession;
    }

    protected function syncCategories(&$confession, $categories)
    {
        if ($categories == null) {
            $categories = [];
        }

        $confession->categories()->sync($categories);
        return $confession;
    }

    protected function getTagNamesFromContent($content)
    {
        preg_match_all('/(#\w+)/', $content, $matches);
        return array_unique(array_shift($matches));
    }

}
{'fraction_non_alphanumeric': 0.15825907065563335, 'fraction_numerical': 0.00047740292807129216, 'mean_word_length': 1.8162670849204572, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 173, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7588103', 'n_tokens_mistral': 3610, 'n_tokens_neox': 3477, 'n_words': 611}